babylon.no-module.max.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  7. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  8. */
  9. var EffectFallbacks = /** @class */ (function () {
  10. function EffectFallbacks() {
  11. this._defines = {};
  12. this._currentRank = 32;
  13. this._maxRank = -1;
  14. }
  15. /**
  16. * Removes the fallback from the bound mesh.
  17. */
  18. EffectFallbacks.prototype.unBindMesh = function () {
  19. this._mesh = null;
  20. };
  21. /**
  22. * Adds a fallback on the specified property.
  23. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  24. * @param define The name of the define in the shader
  25. */
  26. EffectFallbacks.prototype.addFallback = function (rank, define) {
  27. if (!this._defines[rank]) {
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. this._defines[rank] = new Array();
  35. }
  36. this._defines[rank].push(define);
  37. };
  38. /**
  39. * Sets the mesh to use CPU skinning when needing to fallback.
  40. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  41. * @param mesh The mesh to use the fallbacks.
  42. */
  43. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  44. this._mesh = mesh;
  45. if (rank < this._currentRank) {
  46. this._currentRank = rank;
  47. }
  48. if (rank > this._maxRank) {
  49. this._maxRank = rank;
  50. }
  51. };
  52. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  53. /**
  54. * Checks to see if more fallbacks are still availible.
  55. */
  56. get: function () {
  57. return this._currentRank <= this._maxRank;
  58. },
  59. enumerable: true,
  60. configurable: true
  61. });
  62. /**
  63. * Removes the defines that shoould be removed when falling back.
  64. * @param currentDefines defines the current define statements for the shader.
  65. * @param effect defines the current effect we try to compile
  66. * @returns The resulting defines with defines of the current rank removed.
  67. */
  68. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  69. // First we try to switch to CPU skinning
  70. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  71. this._mesh.computeBonesUsingShaders = false;
  72. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  73. effect._bonesComputationForcedToCPU = true;
  74. var scene = this._mesh.getScene();
  75. for (var index = 0; index < scene.meshes.length; index++) {
  76. var otherMesh = scene.meshes[index];
  77. if (!otherMesh.material) {
  78. continue;
  79. }
  80. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  81. continue;
  82. }
  83. if (otherMesh.material.getEffect() === effect) {
  84. otherMesh.computeBonesUsingShaders = false;
  85. }
  86. else if (otherMesh.subMeshes) {
  87. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  88. var subMesh = _a[_i];
  89. var subMeshEffect = subMesh.effect;
  90. if (subMeshEffect === effect) {
  91. otherMesh.computeBonesUsingShaders = false;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. }
  98. else {
  99. var currentFallbacks = this._defines[this._currentRank];
  100. if (currentFallbacks) {
  101. for (var index = 0; index < currentFallbacks.length; index++) {
  102. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  103. }
  104. }
  105. this._currentRank++;
  106. }
  107. return currentDefines;
  108. };
  109. return EffectFallbacks;
  110. }());
  111. BABYLON.EffectFallbacks = EffectFallbacks;
  112. /**
  113. * Options to be used when creating an effect.
  114. */
  115. var EffectCreationOptions = /** @class */ (function () {
  116. function EffectCreationOptions() {
  117. }
  118. return EffectCreationOptions;
  119. }());
  120. BABYLON.EffectCreationOptions = EffectCreationOptions;
  121. /**
  122. * Effect containing vertex and fragment shader that can be executed on an object.
  123. */
  124. var Effect = /** @class */ (function () {
  125. /**
  126. * Instantiates an effect.
  127. * An effect can be used to create/manage/execute vertex and fragment shaders.
  128. * @param baseName Name of the effect.
  129. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  130. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  131. * @param samplers List of sampler variables that will be passed to the shader.
  132. * @param engine Engine to be used to render the effect
  133. * @param defines Define statements to be added to the shader.
  134. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  135. * @param onCompiled Callback that will be called when the shader is compiled.
  136. * @param onError Callback that will be called if an error occurs during shader compilation.
  137. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  138. */
  139. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  140. if (samplers === void 0) { samplers = null; }
  141. if (defines === void 0) { defines = null; }
  142. if (fallbacks === void 0) { fallbacks = null; }
  143. if (onCompiled === void 0) { onCompiled = null; }
  144. if (onError === void 0) { onError = null; }
  145. var _this = this;
  146. /**
  147. * Unique ID of the effect.
  148. */
  149. this.uniqueId = 0;
  150. /**
  151. * Observable that will be called when the shader is compiled.
  152. */
  153. this.onCompileObservable = new BABYLON.Observable();
  154. /**
  155. * Observable that will be called if an error occurs during shader compilation.
  156. */
  157. this.onErrorObservable = new BABYLON.Observable();
  158. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  414. // Rebuild shaders source code
  415. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  416. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  417. vertexCode = prefix + vertexCode;
  418. fragmentCode = prefix + fragmentCode;
  419. // Number lines of shaders source code
  420. var i = 2;
  421. var regex = /\n/gm;
  422. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. i = 2;
  424. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  425. // Dump shaders name and formatted source code
  426. if (this.name.vertexElement) {
  427. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  428. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  429. }
  430. else if (this.name.vertex) {
  431. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  432. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  433. }
  434. else {
  435. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  436. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  437. }
  438. };
  439. ;
  440. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  441. var preparedSourceCode = this._processPrecision(sourceCode);
  442. if (this._engine.webGLVersion == 1) {
  443. callback(preparedSourceCode);
  444. return;
  445. }
  446. // Already converted
  447. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  448. callback(preparedSourceCode.replace("#version 300 es", ""));
  449. return;
  450. }
  451. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  452. // Remove extensions
  453. // #extension GL_OES_standard_derivatives : enable
  454. // #extension GL_EXT_shader_texture_lod : enable
  455. // #extension GL_EXT_frag_depth : enable
  456. // #extension GL_EXT_draw_buffers : require
  457. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  458. var result = preparedSourceCode.replace(regex, "");
  459. // Migrate to GLSL v300
  460. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  461. result = result.replace(/attribute[ \t]/g, "in ");
  462. result = result.replace(/[ \t]attribute/g, " in");
  463. if (isFragment) {
  464. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  465. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/texture2D\s*\(/g, "texture(");
  467. result = result.replace(/textureCube\s*\(/g, "texture(");
  468. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  469. result = result.replace(/gl_FragColor/g, "glFragColor");
  470. result = result.replace(/gl_FragData/g, "glFragData");
  471. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  472. }
  473. callback(result);
  474. };
  475. Effect.prototype._processIncludes = function (sourceCode, callback) {
  476. var _this = this;
  477. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  478. var match = regex.exec(sourceCode);
  479. var returnValue = new String(sourceCode);
  480. while (match != null) {
  481. var includeFile = match[1];
  482. // Uniform declaration
  483. if (includeFile.indexOf("__decl__") !== -1) {
  484. includeFile = includeFile.replace(/__decl__/, "");
  485. if (this._engine.supportsUniformBuffers) {
  486. includeFile = includeFile.replace(/Vertex/, "Ubo");
  487. includeFile = includeFile.replace(/Fragment/, "Ubo");
  488. }
  489. includeFile = includeFile + "Declaration";
  490. }
  491. if (Effect.IncludesShadersStore[includeFile]) {
  492. // Substitution
  493. var includeContent = Effect.IncludesShadersStore[includeFile];
  494. if (match[2]) {
  495. var splits = match[3].split(",");
  496. for (var index = 0; index < splits.length; index += 2) {
  497. var source = new RegExp(splits[index], "g");
  498. var dest = splits[index + 1];
  499. includeContent = includeContent.replace(source, dest);
  500. }
  501. }
  502. if (match[4]) {
  503. var indexString = match[5];
  504. if (indexString.indexOf("..") !== -1) {
  505. var indexSplits = indexString.split("..");
  506. var minIndex = parseInt(indexSplits[0]);
  507. var maxIndex = parseInt(indexSplits[1]);
  508. var sourceIncludeContent = includeContent.slice(0);
  509. includeContent = "";
  510. if (isNaN(maxIndex)) {
  511. maxIndex = this._indexParameters[indexSplits[1]];
  512. }
  513. for (var i = minIndex; i < maxIndex; i++) {
  514. if (!this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  521. }
  522. }
  523. else {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent = includeContent.replace(/\{X\}/g, indexString);
  531. }
  532. }
  533. // Replace
  534. returnValue = returnValue.replace(match[0], includeContent);
  535. }
  536. else {
  537. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  538. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  539. Effect.IncludesShadersStore[includeFile] = fileContent;
  540. _this._processIncludes(returnValue, callback);
  541. });
  542. return;
  543. }
  544. match = regex.exec(sourceCode);
  545. }
  546. callback(returnValue);
  547. };
  548. Effect.prototype._processPrecision = function (source) {
  549. if (source.indexOf("precision highp float") === -1) {
  550. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  551. source = "precision mediump float;\n" + source;
  552. }
  553. else {
  554. source = "precision highp float;\n" + source;
  555. }
  556. }
  557. else {
  558. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  559. source = source.replace("precision highp float", "precision mediump float");
  560. }
  561. }
  562. return source;
  563. };
  564. /**
  565. * Recompiles the webGL program
  566. * @param vertexSourceCode The source code for the vertex shader.
  567. * @param fragmentSourceCode The source code for the fragment shader.
  568. * @param onCompiled Callback called when completed.
  569. * @param onError Callback called on error.
  570. */
  571. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  572. var _this = this;
  573. this._isReady = false;
  574. this._vertexSourceCodeOverride = vertexSourceCode;
  575. this._fragmentSourceCodeOverride = fragmentSourceCode;
  576. this.onError = function (effect, error) {
  577. if (onError) {
  578. onError(error);
  579. }
  580. };
  581. this.onCompiled = function () {
  582. var scenes = _this.getEngine().scenes;
  583. for (var i = 0; i < scenes.length; i++) {
  584. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  585. }
  586. if (onCompiled) {
  587. onCompiled(_this._program);
  588. }
  589. };
  590. this._fallbacks = null;
  591. this._prepareEffect();
  592. };
  593. /**
  594. * Gets the uniform locations of the the specified variable names
  595. * @param names THe names of the variables to lookup.
  596. * @returns Array of locations in the same order as variable names.
  597. */
  598. Effect.prototype.getSpecificUniformLocations = function (names) {
  599. var engine = this._engine;
  600. return engine.getUniforms(this._program, names);
  601. };
  602. /**
  603. * Prepares the effect
  604. */
  605. Effect.prototype._prepareEffect = function () {
  606. var attributesNames = this._attributesNames;
  607. var defines = this.defines;
  608. var fallbacks = this._fallbacks;
  609. this._valueCache = {};
  610. var previousProgram = this._program;
  611. try {
  612. var engine = this._engine;
  613. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  614. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  615. }
  616. else {
  617. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  618. }
  619. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  620. if (engine.supportsUniformBuffers) {
  621. for (var name in this._uniformBuffersNames) {
  622. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  623. }
  624. }
  625. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  626. this._attributes = engine.getAttributes(this._program, attributesNames);
  627. var index;
  628. for (index = 0; index < this._samplers.length; index++) {
  629. var sampler = this.getUniform(this._samplers[index]);
  630. if (sampler == null) {
  631. this._samplers.splice(index, 1);
  632. index--;
  633. }
  634. }
  635. engine.bindSamplers(this);
  636. this._compilationError = "";
  637. this._isReady = true;
  638. if (this.onCompiled) {
  639. this.onCompiled(this);
  640. }
  641. this.onCompileObservable.notifyObservers(this);
  642. this.onCompileObservable.clear();
  643. // Unbind mesh reference in fallbacks
  644. if (this._fallbacks) {
  645. this._fallbacks.unBindMesh();
  646. }
  647. if (previousProgram) {
  648. this.getEngine()._deleteProgram(previousProgram);
  649. }
  650. }
  651. catch (e) {
  652. this._compilationError = e.message;
  653. // Let's go through fallbacks then
  654. BABYLON.Tools.Error("Unable to compile effect:");
  655. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  656. return " " + uniform;
  657. }));
  658. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  659. return " " + attribute;
  660. }));
  661. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * 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)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * 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)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * 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)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * 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)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * 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)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * 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)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * 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)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * 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)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * 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)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * 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)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * 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)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  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. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * 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.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. if (x === void 0) { x = 0; }
  2190. if (y === void 0) { y = 0; }
  2191. this.x = x;
  2192. this.y = y;
  2193. }
  2194. /**
  2195. * Gets a string with the Vector2 coordinates
  2196. * @returns a string with the Vector2 coordinates
  2197. */
  2198. Vector2.prototype.toString = function () {
  2199. return "{X: " + this.x + " Y:" + this.y + "}";
  2200. };
  2201. /**
  2202. * Gets class name
  2203. * @returns the string "Vector2"
  2204. */
  2205. Vector2.prototype.getClassName = function () {
  2206. return "Vector2";
  2207. };
  2208. /**
  2209. * Gets current vector hash code
  2210. * @returns the Vector2 hash code as a number
  2211. */
  2212. Vector2.prototype.getHashCode = function () {
  2213. var hash = this.x || 0;
  2214. hash = (hash * 397) ^ (this.y || 0);
  2215. return hash;
  2216. };
  2217. // Operators
  2218. /**
  2219. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2220. * @param array defines the source array
  2221. * @param index defines the offset in source array
  2222. * @returns the current Vector2
  2223. */
  2224. Vector2.prototype.toArray = function (array, index) {
  2225. if (index === void 0) { index = 0; }
  2226. array[index] = this.x;
  2227. array[index + 1] = this.y;
  2228. return this;
  2229. };
  2230. /**
  2231. * Copy the current vector to an array
  2232. * @returns a new array with 2 elements: the Vector2 coordinates.
  2233. */
  2234. Vector2.prototype.asArray = function () {
  2235. var result = new Array();
  2236. this.toArray(result, 0);
  2237. return result;
  2238. };
  2239. /**
  2240. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2241. * @param source defines the source Vector2
  2242. * @returns the current updated Vector2
  2243. */
  2244. Vector2.prototype.copyFrom = function (source) {
  2245. this.x = source.x;
  2246. this.y = source.y;
  2247. return this;
  2248. };
  2249. /**
  2250. * Sets the Vector2 coordinates with the given floats
  2251. * @param x defines the first coordinate
  2252. * @param y defines the second coordinate
  2253. * @returns the current updated Vector2
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given floats
  2262. * @param x defines the first coordinate
  2263. * @param y defines the second coordinate
  2264. * @returns the current updated Vector2
  2265. */
  2266. Vector2.prototype.set = function (x, y) {
  2267. return this.copyFromFloats(x, y);
  2268. };
  2269. /**
  2270. * Add another vector with the current one
  2271. * @param otherVector defines the other vector
  2272. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2273. */
  2274. Vector2.prototype.add = function (otherVector) {
  2275. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2279. * @param otherVector defines the other vector
  2280. * @param result defines the target vector
  2281. * @returns the unmodified current Vector2
  2282. */
  2283. Vector2.prototype.addToRef = function (otherVector, result) {
  2284. result.x = this.x + otherVector.x;
  2285. result.y = this.y + otherVector.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2290. * @param otherVector defines the other vector
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.addInPlace = function (otherVector) {
  2294. this.x += otherVector.x;
  2295. this.y += otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2300. * @param otherVector defines the other vector
  2301. * @returns a new Vector2
  2302. */
  2303. Vector2.prototype.addVector3 = function (otherVector) {
  2304. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2305. };
  2306. /**
  2307. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2308. * @param otherVector defines the other vector
  2309. * @returns a new Vector2
  2310. */
  2311. Vector2.prototype.subtract = function (otherVector) {
  2312. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2316. * @param otherVector defines the other vector
  2317. * @param result defines the target vector
  2318. * @returns the unmodified current Vector2
  2319. */
  2320. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2321. result.x = this.x - otherVector.x;
  2322. result.y = this.y - otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns the current updated Vector2
  2329. */
  2330. Vector2.prototype.subtractInPlace = function (otherVector) {
  2331. this.x -= otherVector.x;
  2332. this.y -= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Multiplies in place the current Vector2 coordinates by the given ones
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2341. this.x *= otherVector.x;
  2342. this.y *= otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.multiply = function (otherVector) {
  2351. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2352. };
  2353. /**
  2354. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2355. * @param otherVector defines the other vector
  2356. * @param result defines the target vector
  2357. * @returns the unmodified current Vector2
  2358. */
  2359. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2360. result.x = this.x * otherVector.x;
  2361. result.y = this.y * otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2366. * @param x defines the first coordinate
  2367. * @param y defines the second coordinate
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2375. * @param otherVector defines the other vector
  2376. * @returns a new Vector2
  2377. */
  2378. Vector2.prototype.divide = function (otherVector) {
  2379. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2380. };
  2381. /**
  2382. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2383. * @param otherVector defines the other vector
  2384. * @param result defines the target vector
  2385. * @returns the unmodified current Vector2
  2386. */
  2387. Vector2.prototype.divideToRef = function (otherVector, result) {
  2388. result.x = this.x / otherVector.x;
  2389. result.y = this.y / otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Divides the current Vector3 coordinates by the given ones
  2394. * @param otherVector defines the other vector
  2395. * @returns the current updated Vector2
  2396. */
  2397. Vector2.prototype.divideInPlace = function (otherVector) {
  2398. return this.divideToRef(otherVector, this);
  2399. };
  2400. /**
  2401. * Gets a new Vector2 with current Vector2 negated coordinates
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.negate = function () {
  2405. return new Vector2(-this.x, -this.y);
  2406. };
  2407. /**
  2408. * Multiply the Vector2 coordinates by scale
  2409. * @param scale defines the scaling factor
  2410. * @returns the current updated Vector2
  2411. */
  2412. Vector2.prototype.scaleInPlace = function (scale) {
  2413. this.x *= scale;
  2414. this.y *= scale;
  2415. return this;
  2416. };
  2417. /**
  2418. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2419. * @param scale defines the scaling factor
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.scale = function (scale) {
  2423. var result = new Vector2(0, 0);
  2424. this.scaleToRef(scale, result);
  2425. return result;
  2426. };
  2427. /**
  2428. * Scale the current Vector2 values by a factor to a given Vector2
  2429. * @param scale defines the scale factor
  2430. * @param result defines the Vector2 object where to store the result
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.scaleToRef = function (scale, result) {
  2434. result.x = this.x * scale;
  2435. result.y = this.y * scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2440. * @param scale defines the scale factor
  2441. * @param result defines the Vector2 object where to store the result
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2445. result.x += this.x * scale;
  2446. result.y += this.y * scale;
  2447. return this;
  2448. };
  2449. /**
  2450. * Gets a boolean if two vectors are equals
  2451. * @param otherVector defines the other vector
  2452. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2453. */
  2454. Vector2.prototype.equals = function (otherVector) {
  2455. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2456. };
  2457. /**
  2458. * Gets a boolean if two vectors are equals (using an epsilon value)
  2459. * @param otherVector defines the other vector
  2460. * @param epsilon defines the minimal distance to consider equality
  2461. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2462. */
  2463. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2464. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2465. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2466. };
  2467. // Properties
  2468. /**
  2469. * Gets the length of the vector
  2470. * @returns the vector length (float)
  2471. */
  2472. Vector2.prototype.length = function () {
  2473. return Math.sqrt(this.x * this.x + this.y * this.y);
  2474. };
  2475. /**
  2476. * Gets the vector squared length
  2477. * @returns the vector squared length (float)
  2478. */
  2479. Vector2.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y);
  2481. };
  2482. // Methods
  2483. /**
  2484. * Normalize the vector
  2485. * @returns the current updated Vector2
  2486. */
  2487. Vector2.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a new Vector2 copied from the Vector2
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.clone = function () {
  2501. return new Vector2(this.x, this.y);
  2502. };
  2503. // Statics
  2504. /**
  2505. * Gets a new Vector2(0, 0)
  2506. * @returns a new Vector2
  2507. */
  2508. Vector2.Zero = function () {
  2509. return new Vector2(0, 0);
  2510. };
  2511. /**
  2512. * Gets a new Vector2(1, 1)
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.One = function () {
  2516. return new Vector2(1, 1);
  2517. };
  2518. /**
  2519. * Gets a new Vector2 set from the given index element of the given array
  2520. * @param array defines the data source
  2521. * @param offset defines the offset in the data source
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.FromArray = function (array, offset) {
  2525. if (offset === void 0) { offset = 0; }
  2526. return new Vector2(array[offset], array[offset + 1]);
  2527. };
  2528. /**
  2529. * Sets "result" from the given index element of the given array
  2530. * @param array defines the data source
  2531. * @param offset defines the offset in the data source
  2532. * @param result defines the target vector
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2540. * @param value1 defines 1st point of control
  2541. * @param value2 defines 2nd point of control
  2542. * @param value3 defines 3rd point of control
  2543. * @param value4 defines 4th point of control
  2544. * @param amount defines the interpolation factor
  2545. * @returns a new Vector2
  2546. */
  2547. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2548. var squared = amount * amount;
  2549. var cubed = amount * squared;
  2550. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2551. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2552. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2553. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2554. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2555. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2556. return new Vector2(x, y);
  2557. };
  2558. /**
  2559. * 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".
  2560. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2561. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2562. * @param value defines the value to clamp
  2563. * @param min defines the lower limit
  2564. * @param max defines the upper limit
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.Clamp = function (value, min, max) {
  2568. var x = value.x;
  2569. x = (x > max.x) ? max.x : x;
  2570. x = (x < min.x) ? min.x : x;
  2571. var y = value.y;
  2572. y = (y > max.y) ? max.y : y;
  2573. y = (y < min.y) ? min.y : y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2578. * @param value1 defines the 1st control point
  2579. * @param tangent1 defines the outgoing tangent
  2580. * @param value2 defines the 2nd control point
  2581. * @param tangent2 defines the incoming tangent
  2582. * @param amount defines the interpolation factor
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2586. var squared = amount * amount;
  2587. var cubed = amount * squared;
  2588. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2589. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2590. var part3 = (cubed - (2.0 * squared)) + amount;
  2591. var part4 = cubed - squared;
  2592. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2593. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2594. return new Vector2(x, y);
  2595. };
  2596. /**
  2597. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2598. * @param start defines the start vector
  2599. * @param end defines the end vector
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Lerp = function (start, end, amount) {
  2604. var x = start.x + ((end.x - start.x) * amount);
  2605. var y = start.y + ((end.y - start.y) * amount);
  2606. return new Vector2(x, y);
  2607. };
  2608. /**
  2609. * Gets the dot product of the vector "left" and the vector "right"
  2610. * @param left defines first vector
  2611. * @param right defines second vector
  2612. * @returns the dot product (float)
  2613. */
  2614. Vector2.Dot = function (left, right) {
  2615. return left.x * right.x + left.y * right.y;
  2616. };
  2617. /**
  2618. * Returns a new Vector2 equal to the normalized given vector
  2619. * @param vector defines the vector to normalize
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Normalize = function (vector) {
  2623. var newVector = vector.clone();
  2624. newVector.normalize();
  2625. return newVector;
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2629. * @param left defines 1st vector
  2630. * @param right defines 2nd vector
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.Minimize = function (left, right) {
  2634. var x = (left.x < right.x) ? left.x : right.x;
  2635. var y = (left.y < right.y) ? left.y : right.y;
  2636. return new Vector2(x, y);
  2637. };
  2638. /**
  2639. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2640. * @param left defines 1st vector
  2641. * @param right defines 2nd vector
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Maximize = function (left, right) {
  2645. var x = (left.x > right.x) ? left.x : right.x;
  2646. var y = (left.y > right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2651. * @param vector defines the vector to transform
  2652. * @param transformation defines the matrix to apply
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Transform = function (vector, transformation) {
  2656. var r = Vector2.Zero();
  2657. Vector2.TransformToRef(vector, transformation, r);
  2658. return r;
  2659. };
  2660. /**
  2661. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2662. * @param vector defines the vector to transform
  2663. * @param transformation defines the matrix to apply
  2664. * @param result defines the target vector
  2665. */
  2666. Vector2.TransformToRef = function (vector, transformation, result) {
  2667. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2668. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2669. result.x = x;
  2670. result.y = y;
  2671. };
  2672. /**
  2673. * Determines if a given vector is included in a triangle
  2674. * @param p defines the vector to test
  2675. * @param p0 defines 1st triangle point
  2676. * @param p1 defines 2nd triangle point
  2677. * @param p2 defines 3rd triangle point
  2678. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2679. */
  2680. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2681. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2682. var sign = a < 0 ? -1 : 1;
  2683. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2684. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2685. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2686. };
  2687. /**
  2688. * Gets the distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the distance between vectors
  2692. */
  2693. Vector2.Distance = function (value1, value2) {
  2694. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2695. };
  2696. /**
  2697. * Returns the squared distance between the vectors "value1" and "value2"
  2698. * @param value1 defines first vector
  2699. * @param value2 defines second vector
  2700. * @returns the squared distance between vectors
  2701. */
  2702. Vector2.DistanceSquared = function (value1, value2) {
  2703. var x = value1.x - value2.x;
  2704. var y = value1.y - value2.y;
  2705. return (x * x) + (y * y);
  2706. };
  2707. /**
  2708. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2709. * @param value1 defines first vector
  2710. * @param value2 defines second vector
  2711. * @returns a new Vector2
  2712. */
  2713. Vector2.Center = function (value1, value2) {
  2714. var center = value1.add(value2);
  2715. center.scaleInPlace(0.5);
  2716. return center;
  2717. };
  2718. /**
  2719. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2720. * @param p defines the middle point
  2721. * @param segA defines one point of the segment
  2722. * @param segB defines the other point of the segment
  2723. * @returns the shortest distance
  2724. */
  2725. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2726. var l2 = Vector2.DistanceSquared(segA, segB);
  2727. if (l2 === 0.0) {
  2728. return Vector2.Distance(p, segA);
  2729. }
  2730. var v = segB.subtract(segA);
  2731. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2732. var proj = segA.add(v.multiplyByFloats(t, t));
  2733. return Vector2.Distance(p, proj);
  2734. };
  2735. return Vector2;
  2736. }());
  2737. BABYLON.Vector2 = Vector2;
  2738. /**
  2739. * Classed used to store (x,y,z) vector representation
  2740. * A Vector3 is the main object used in 3D geometry
  2741. * It can represent etiher the coordinates of a point the space, either a direction
  2742. * Reminder: Babylon.js uses a left handed forward facing system
  2743. */
  2744. var Vector3 = /** @class */ (function () {
  2745. /**
  2746. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2747. * @param x defines the first coordinates (on X axis)
  2748. * @param y defines the second coordinates (on Y axis)
  2749. * @param z defines the third coordinates (on Z axis)
  2750. */
  2751. function Vector3(
  2752. /**
  2753. * Defines the first coordinates (on X axis)
  2754. */
  2755. x,
  2756. /**
  2757. * Defines the second coordinates (on Y axis)
  2758. */
  2759. y,
  2760. /**
  2761. * Defines the third coordinates (on Z axis)
  2762. */
  2763. z) {
  2764. if (x === void 0) { x = 0; }
  2765. if (y === void 0) { y = 0; }
  2766. if (z === void 0) { z = 0; }
  2767. this.x = x;
  2768. this.y = y;
  2769. this.z = z;
  2770. }
  2771. /**
  2772. * Creates a string representation of the Vector3
  2773. * @returns a string with the Vector3 coordinates.
  2774. */
  2775. Vector3.prototype.toString = function () {
  2776. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2777. };
  2778. /**
  2779. * Gets the class name
  2780. * @returns the string "Vector3"
  2781. */
  2782. Vector3.prototype.getClassName = function () {
  2783. return "Vector3";
  2784. };
  2785. /**
  2786. * Creates the Vector3 hash code
  2787. * @returns a number which tends to be unique between Vector3 instances
  2788. */
  2789. Vector3.prototype.getHashCode = function () {
  2790. var hash = this.x || 0;
  2791. hash = (hash * 397) ^ (this.y || 0);
  2792. hash = (hash * 397) ^ (this.z || 0);
  2793. return hash;
  2794. };
  2795. // Operators
  2796. /**
  2797. * Creates an array containing three elements : the coordinates of the Vector3
  2798. * @returns a new array of numbers
  2799. */
  2800. Vector3.prototype.asArray = function () {
  2801. var result = [];
  2802. this.toArray(result, 0);
  2803. return result;
  2804. };
  2805. /**
  2806. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2807. * @param array defines the destination array
  2808. * @param index defines the offset in the destination array
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.toArray = function (array, index) {
  2812. if (index === void 0) { index = 0; }
  2813. array[index] = this.x;
  2814. array[index + 1] = this.y;
  2815. array[index + 2] = this.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2820. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2821. */
  2822. Vector3.prototype.toQuaternion = function () {
  2823. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2824. };
  2825. /**
  2826. * Adds the given vector to the current Vector3
  2827. * @param otherVector defines the second operand
  2828. * @returns the current updated Vector3
  2829. */
  2830. Vector3.prototype.addInPlace = function (otherVector) {
  2831. this.x += otherVector.x;
  2832. this.y += otherVector.y;
  2833. this.z += otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2838. * @param otherVector defines the second operand
  2839. * @returns the resulting Vector3
  2840. */
  2841. Vector3.prototype.add = function (otherVector) {
  2842. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2843. };
  2844. /**
  2845. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2846. * @param otherVector defines the second operand
  2847. * @param result defines the Vector3 object where to store the result
  2848. * @returns the current Vector3
  2849. */
  2850. Vector3.prototype.addToRef = function (otherVector, result) {
  2851. result.x = this.x + otherVector.x;
  2852. result.y = this.y + otherVector.y;
  2853. result.z = this.z + otherVector.z;
  2854. return this;
  2855. };
  2856. /**
  2857. * Subtract the given vector from the current Vector3
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.subtractInPlace = function (otherVector) {
  2862. this.x -= otherVector.x;
  2863. this.y -= otherVector.y;
  2864. this.z -= otherVector.z;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2869. * @param otherVector defines the second operand
  2870. * @returns the resulting Vector3
  2871. */
  2872. Vector3.prototype.subtract = function (otherVector) {
  2873. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2874. };
  2875. /**
  2876. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2877. * @param otherVector defines the second operand
  2878. * @param result defines the Vector3 object where to store the result
  2879. * @returns the current Vector3
  2880. */
  2881. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2882. result.x = this.x - otherVector.x;
  2883. result.y = this.y - otherVector.y;
  2884. result.z = this.z - otherVector.z;
  2885. return this;
  2886. };
  2887. /**
  2888. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2889. * @param x defines the x coordinate of the operand
  2890. * @param y defines the y coordinate of the operand
  2891. * @param z defines the z coordinate of the operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2895. return new Vector3(this.x - x, this.y - y, this.z - z);
  2896. };
  2897. /**
  2898. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2899. * @param x defines the x coordinate of the operand
  2900. * @param y defines the y coordinate of the operand
  2901. * @param z defines the z coordinate of the operand
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2906. result.x = this.x - x;
  2907. result.y = this.y - y;
  2908. result.z = this.z - z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2913. * @returns a new Vector3
  2914. */
  2915. Vector3.prototype.negate = function () {
  2916. return new Vector3(-this.x, -this.y, -this.z);
  2917. };
  2918. /**
  2919. * Multiplies the Vector3 coordinates by the float "scale"
  2920. * @param scale defines the multiplier factor
  2921. * @returns the current updated Vector3
  2922. */
  2923. Vector3.prototype.scaleInPlace = function (scale) {
  2924. this.x *= scale;
  2925. this.y *= scale;
  2926. this.z *= scale;
  2927. return this;
  2928. };
  2929. /**
  2930. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2931. * @param scale defines the multiplier factor
  2932. * @returns a new Vector3
  2933. */
  2934. Vector3.prototype.scale = function (scale) {
  2935. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2936. };
  2937. /**
  2938. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2939. * @param scale defines the multiplier factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the current Vector3
  2942. */
  2943. Vector3.prototype.scaleToRef = function (scale, result) {
  2944. result.x = this.x * scale;
  2945. result.y = this.y * scale;
  2946. result.z = this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2951. * @param scale defines the scale factor
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the unmodified current Vector3
  2954. */
  2955. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2956. result.x += this.x * scale;
  2957. result.y += this.y * scale;
  2958. result.z += this.z * scale;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2963. * @param otherVector defines the second operand
  2964. * @returns true if both vectors are equals
  2965. */
  2966. Vector3.prototype.equals = function (otherVector) {
  2967. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2968. };
  2969. /**
  2970. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2971. * @param otherVector defines the second operand
  2972. * @param epsilon defines the minimal distance to define values as equals
  2973. * @returns true if both vectors are distant less than epsilon
  2974. */
  2975. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2976. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2977. 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);
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 coordinates equals the given floats
  2981. * @param x defines the x coordinate of the operand
  2982. * @param y defines the y coordinate of the operand
  2983. * @param z defines the z coordinate of the operand
  2984. * @returns true if both vectors are equals
  2985. */
  2986. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2987. return this.x === x && this.y === y && this.z === z;
  2988. };
  2989. /**
  2990. * Multiplies the current Vector3 coordinates by the given ones
  2991. * @param otherVector defines the second operand
  2992. * @returns the current updated Vector3
  2993. */
  2994. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2995. this.x *= otherVector.x;
  2996. this.y *= otherVector.y;
  2997. this.z *= otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3002. * @param otherVector defines the second operand
  3003. * @returns the new Vector3
  3004. */
  3005. Vector3.prototype.multiply = function (otherVector) {
  3006. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3007. };
  3008. /**
  3009. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3010. * @param otherVector defines the second operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3015. result.x = this.x * otherVector.x;
  3016. result.y = this.y * otherVector.y;
  3017. result.z = this.z * otherVector.z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3028. return new Vector3(this.x * x, this.y * y, this.z * z);
  3029. };
  3030. /**
  3031. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3032. * @param otherVector defines the second operand
  3033. * @returns the new Vector3
  3034. */
  3035. Vector3.prototype.divide = function (otherVector) {
  3036. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3040. * @param otherVector defines the second operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.divideToRef = function (otherVector, result) {
  3045. result.x = this.x / otherVector.x;
  3046. result.y = this.y / otherVector.y;
  3047. result.z = this.z / otherVector.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Divides the current Vector3 coordinates by the given ones.
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.divideInPlace = function (otherVector) {
  3056. return this.divideToRef(otherVector, this);
  3057. };
  3058. /**
  3059. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3060. * @param other defines the second operand
  3061. * @returns the current updated Vector3
  3062. */
  3063. Vector3.prototype.minimizeInPlace = function (other) {
  3064. if (other.x < this.x)
  3065. this.x = other.x;
  3066. if (other.y < this.y)
  3067. this.y = other.y;
  3068. if (other.z < this.z)
  3069. this.z = other.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3074. * @param other defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.maximizeInPlace = function (other) {
  3078. if (other.x > this.x)
  3079. this.x = other.x;
  3080. if (other.y > this.y)
  3081. this.y = other.y;
  3082. if (other.z > this.z)
  3083. this.z = other.z;
  3084. return this;
  3085. };
  3086. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3087. /**
  3088. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3089. */
  3090. get: function () {
  3091. var absX = Math.abs(this.x);
  3092. var absY = Math.abs(this.y);
  3093. if (absX !== absY) {
  3094. return true;
  3095. }
  3096. var absZ = Math.abs(this.z);
  3097. if (absX !== absZ) {
  3098. return true;
  3099. }
  3100. if (absY !== absZ) {
  3101. return true;
  3102. }
  3103. return false;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. // Properties
  3109. /**
  3110. * Gets the length of the Vector3
  3111. * @returns the length of the Vecto3
  3112. */
  3113. Vector3.prototype.length = function () {
  3114. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3115. };
  3116. /**
  3117. * Gets the squared length of the Vector3
  3118. * @returns squared length of the Vector3
  3119. */
  3120. Vector3.prototype.lengthSquared = function () {
  3121. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3122. };
  3123. /**
  3124. * Normalize the current Vector3.
  3125. * Please note that this is an in place operation.
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.normalize = function () {
  3129. var len = this.length();
  3130. if (len === 0 || len === 1.0)
  3131. return this;
  3132. var num = 1.0 / len;
  3133. this.x *= num;
  3134. this.y *= num;
  3135. this.z *= num;
  3136. return this;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to a new vector
  3140. * @returns the new Vector3
  3141. */
  3142. Vector3.prototype.normalizeToNew = function () {
  3143. var normalized = new Vector3(0, 0, 0);
  3144. this.normalizeToRef(normalized);
  3145. return normalized;
  3146. };
  3147. /**
  3148. * Normalize the current Vector3 to the reference
  3149. * @param reference define the Vector3 to update
  3150. * @returns the updated Vector3
  3151. */
  3152. Vector3.prototype.normalizeToRef = function (reference) {
  3153. var len = this.length();
  3154. if (len === 0 || len === 1.0) {
  3155. reference.set(this.x, this.y, this.z);
  3156. return reference;
  3157. }
  3158. var scale = 1.0 / len;
  3159. this.scaleToRef(scale, reference);
  3160. return reference;
  3161. };
  3162. /**
  3163. * Creates a new Vector3 copied from the current Vector3
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.clone = function () {
  3167. return new Vector3(this.x, this.y, this.z);
  3168. };
  3169. /**
  3170. * Copies the given vector coordinates to the current Vector3 ones
  3171. * @param source defines the source Vector3
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.copyFrom = function (source) {
  3175. this.x = source.x;
  3176. this.y = source.y;
  3177. this.z = source.z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Copies the given floats to the current Vector3 coordinates
  3182. * @param x defines the x coordinate of the operand
  3183. * @param y defines the y coordinate of the operand
  3184. * @param z defines the z coordinate of the operand
  3185. * @returns the current updated Vector3
  3186. */
  3187. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3188. this.x = x;
  3189. this.y = y;
  3190. this.z = z;
  3191. return this;
  3192. };
  3193. /**
  3194. * Copies the given floats to the current Vector3 coordinates
  3195. * @param x defines the x coordinate of the operand
  3196. * @param y defines the y coordinate of the operand
  3197. * @param z defines the z coordinate of the operand
  3198. * @returns the current updated Vector3
  3199. */
  3200. Vector3.prototype.set = function (x, y, z) {
  3201. return this.copyFromFloats(x, y, z);
  3202. };
  3203. // Statics
  3204. /**
  3205. * Get the clip factor between two vectors
  3206. * @param vector0 defines the first operand
  3207. * @param vector1 defines the second operand
  3208. * @param axis defines the axis to use
  3209. * @param size defines the size along the axis
  3210. * @returns the clip factor
  3211. */
  3212. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3213. var d0 = Vector3.Dot(vector0, axis) - size;
  3214. var d1 = Vector3.Dot(vector1, axis) - size;
  3215. var s = d0 / (d0 - d1);
  3216. return s;
  3217. };
  3218. /**
  3219. * Get angle between two vectors
  3220. * @param vector0 angle between vector0 and vector1
  3221. * @param vector1 angle between vector0 and vector1
  3222. * @param normal direction of the normal
  3223. * @return the angle between vector0 and vector1
  3224. */
  3225. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3226. var v0 = vector0.clone().normalize();
  3227. var v1 = vector1.clone().normalize();
  3228. var dot = Vector3.Dot(v0, v1);
  3229. var n = Vector3.Cross(v0, v1);
  3230. if (Vector3.Dot(n, normal) > 0) {
  3231. return Math.acos(dot);
  3232. }
  3233. return -Math.acos(dot);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given array
  3237. * @param array defines the source array
  3238. * @param offset defines the offset in the source array
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.FromArray = function (array, offset) {
  3242. if (!offset) {
  3243. offset = 0;
  3244. }
  3245. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3249. * This function is deprecated. Use FromArray instead
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @returns the new Vector3
  3253. */
  3254. Vector3.FromFloatArray = function (array, offset) {
  3255. return Vector3.FromArray(array, offset);
  3256. };
  3257. /**
  3258. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromArrayToRef = function (array, offset, result) {
  3264. result.x = array[offset];
  3265. result.y = array[offset + 1];
  3266. result.z = array[offset + 2];
  3267. };
  3268. /**
  3269. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3270. * This function is deprecated. Use FromArrayToRef instead.
  3271. * @param array defines the source array
  3272. * @param offset defines the offset in the source array
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3276. return Vector3.FromArrayToRef(array, offset, result);
  3277. };
  3278. /**
  3279. * Sets the given vector "result" with the given floats.
  3280. * @param x defines the x coordinate of the source
  3281. * @param y defines the y coordinate of the source
  3282. * @param z defines the z coordinate of the source
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3286. result.x = x;
  3287. result.y = y;
  3288. result.z = z;
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3292. * @returns a new empty Vector3
  3293. */
  3294. Vector3.Zero = function () {
  3295. return new Vector3(0.0, 0.0, 0.0);
  3296. };
  3297. /**
  3298. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3299. * @returns a new unit Vector3
  3300. */
  3301. Vector3.One = function () {
  3302. return new Vector3(1.0, 1.0, 1.0);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3306. * @returns a new up Vector3
  3307. */
  3308. Vector3.Up = function () {
  3309. return new Vector3(0.0, 1.0, 0.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3313. * @returns a new down Vector3
  3314. */
  3315. Vector3.Down = function () {
  3316. return new Vector3(0.0, -1.0, 0.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3320. * @returns a new forward Vector3
  3321. */
  3322. Vector3.Forward = function () {
  3323. return new Vector3(0.0, 0.0, 1.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3327. * @returns a new right Vector3
  3328. */
  3329. Vector3.Right = function () {
  3330. return new Vector3(1.0, 0.0, 0.0);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3334. * @returns a new left Vector3
  3335. */
  3336. Vector3.Left = function () {
  3337. return new Vector3(-1.0, 0.0, 0.0);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @returns the transformed Vector3
  3345. */
  3346. Vector3.TransformCoordinates = function (vector, transformation) {
  3347. var result = Vector3.Zero();
  3348. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3349. return result;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3353. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3354. * @param vector defines the Vector3 to transform
  3355. * @param transformation defines the transformation matrix
  3356. * @param result defines the Vector3 where to store the result
  3357. */
  3358. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3359. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3360. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3361. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3362. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3363. result.x = x / w;
  3364. result.y = y / w;
  3365. result.z = z / w;
  3366. };
  3367. /**
  3368. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3369. * This method computes tranformed coordinates only, not transformed direction vectors
  3370. * @param x define the x coordinate of the source vector
  3371. * @param y define the y coordinate of the source vector
  3372. * @param z define the z coordinate of the source vector
  3373. * @param transformation defines the transformation matrix
  3374. * @param result defines the Vector3 where to store the result
  3375. */
  3376. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3377. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3378. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3379. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3380. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3381. result.x = rx / rw;
  3382. result.y = ry / rw;
  3383. result.z = rz / rw;
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.TransformNormal = function (vector, transformation) {
  3393. var result = Vector3.Zero();
  3394. Vector3.TransformNormalToRef(vector, transformation, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param vector defines the Vector3 to transform
  3401. * @param transformation defines the transformation matrix
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3408. result.x = x;
  3409. result.y = y;
  3410. result.z = z;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param x define the x coordinate of the source vector
  3416. * @param y define the y coordinate of the source vector
  3417. * @param z define the z coordinate of the source vector
  3418. * @param transformation defines the transformation matrix
  3419. * @param result defines the Vector3 where to store the result
  3420. */
  3421. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3422. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3423. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3424. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3428. * @param value1 defines the first control point
  3429. * @param value2 defines the second control point
  3430. * @param value3 defines the third control point
  3431. * @param value4 defines the fourth control point
  3432. * @param amount defines the amount on the spline to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3436. var squared = amount * amount;
  3437. var cubed = amount * squared;
  3438. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3439. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3440. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3441. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3442. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3443. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3444. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3445. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3446. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3447. return new Vector3(x, y, z);
  3448. };
  3449. /**
  3450. * 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"
  3451. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3452. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3453. * @param value defines the current value
  3454. * @param min defines the lower range value
  3455. * @param max defines the upper range value
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Clamp = function (value, min, max) {
  3459. var x = value.x;
  3460. x = (x > max.x) ? max.x : x;
  3461. x = (x < min.x) ? min.x : x;
  3462. var y = value.y;
  3463. y = (y > max.y) ? max.y : y;
  3464. y = (y < min.y) ? min.y : y;
  3465. var z = value.z;
  3466. z = (z > max.z) ? max.z : z;
  3467. z = (z < min.z) ? min.z : z;
  3468. return new Vector3(x, y, z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3472. * @param value1 defines the first control point
  3473. * @param tangent1 defines the first tangent vector
  3474. * @param value2 defines the second control point
  3475. * @param tangent2 defines the second tangent vector
  3476. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3480. var squared = amount * amount;
  3481. var cubed = amount * squared;
  3482. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3483. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3484. var part3 = (cubed - (2.0 * squared)) + amount;
  3485. var part4 = cubed - squared;
  3486. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3487. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3488. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3489. return new Vector3(x, y, z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Lerp = function (start, end, amount) {
  3499. var result = new Vector3(0, 0, 0);
  3500. Vector3.LerpToRef(start, end, amount, result);
  3501. return result;
  3502. };
  3503. /**
  3504. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3505. * @param start defines the start value
  3506. * @param end defines the end value
  3507. * @param amount max defines amount between both (between 0 and 1)
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.LerpToRef = function (start, end, amount, result) {
  3511. result.x = start.x + ((end.x - start.x) * amount);
  3512. result.y = start.y + ((end.y - start.y) * amount);
  3513. result.z = start.z + ((end.z - start.z) * amount);
  3514. };
  3515. /**
  3516. * Returns the dot product (float) between the vectors "left" and "right"
  3517. * @param left defines the left operand
  3518. * @param right defines the right operand
  3519. * @returns the dot product
  3520. */
  3521. Vector3.Dot = function (left, right) {
  3522. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @returns the cross product
  3530. */
  3531. Vector3.Cross = function (left, right) {
  3532. var result = Vector3.Zero();
  3533. Vector3.CrossToRef(left, right, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Sets the given vector "result" with the cross product of "left" and "right"
  3538. * The cross product is then orthogonal to both "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @param result defines the Vector3 where to store the result
  3542. */
  3543. Vector3.CrossToRef = function (left, right, result) {
  3544. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3545. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3546. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3547. result.copyFrom(MathTmp.Vector3[0]);
  3548. };
  3549. /**
  3550. * Returns a new Vector3 as the normalization of the given vector
  3551. * @param vector defines the Vector3 to normalize
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Normalize = function (vector) {
  3555. var result = Vector3.Zero();
  3556. Vector3.NormalizeToRef(vector, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the given vector "result" with the normalization of the given first vector
  3561. * @param vector defines the Vector3 to normalize
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.NormalizeToRef = function (vector, result) {
  3565. result.copyFrom(vector);
  3566. result.normalize();
  3567. };
  3568. /**
  3569. * Project a Vector3 onto screen space
  3570. * @param vector defines the Vector3 to project
  3571. * @param world defines the world matrix to use
  3572. * @param transform defines the transform (view x projection) matrix to use
  3573. * @param viewport defines the screen viewport to use
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Project = function (vector, world, transform, viewport) {
  3577. var cw = viewport.width;
  3578. var ch = viewport.height;
  3579. var cx = viewport.x;
  3580. var cy = viewport.y;
  3581. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3582. 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);
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.multiplyToRef(viewportMatrix, matrix);
  3586. return Vector3.TransformCoordinates(vector, matrix);
  3587. };
  3588. /**
  3589. * Unproject from screen space to object space
  3590. * @param source defines the screen space Vector3 to use
  3591. * @param viewportWidth defines the current width of the viewport
  3592. * @param viewportHeight defines the current height of the viewport
  3593. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3594. * @param transform defines the transform (view x projection) matrix to use
  3595. * @returns the new Vector3
  3596. */
  3597. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.invert();
  3601. source.x = source.x / viewportWidth * 2 - 1;
  3602. source.y = -(source.y / viewportHeight * 2 - 1);
  3603. var vector = Vector3.TransformCoordinates(source, matrix);
  3604. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3605. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3606. vector = vector.scale(1.0 / num);
  3607. }
  3608. return vector;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @returns the new Vector3
  3619. */
  3620. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3621. var result = Vector3.Zero();
  3622. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3623. return result;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3637. };
  3638. /**
  3639. * Unproject from screen space to object space
  3640. * @param sourceX defines the screen space x coordinate to use
  3641. * @param sourceY defines the screen space y coordinate to use
  3642. * @param sourceZ defines the screen space z coordinate to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. var matrix = MathTmp.Matrix[0];
  3652. world.multiplyToRef(view, matrix);
  3653. matrix.multiplyToRef(projection, matrix);
  3654. matrix.invert();
  3655. var screenSource = MathTmp.Vector3[0];
  3656. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3657. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3658. screenSource.z = 2 * sourceZ - 1.0;
  3659. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3660. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3661. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3662. result.scaleInPlace(1.0 / num);
  3663. }
  3664. };
  3665. /**
  3666. * Gets the minimal coordinate values between two Vector3
  3667. * @param left defines the first operand
  3668. * @param right defines the second operand
  3669. * @returns the new Vector3
  3670. */
  3671. Vector3.Minimize = function (left, right) {
  3672. var min = left.clone();
  3673. min.minimizeInPlace(right);
  3674. return min;
  3675. };
  3676. /**
  3677. * Gets the maximal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Maximize = function (left, right) {
  3683. var max = left.clone();
  3684. max.maximizeInPlace(right);
  3685. return max;
  3686. };
  3687. /**
  3688. * Returns the distance between the vectors "value1" and "value2"
  3689. * @param value1 defines the first operand
  3690. * @param value2 defines the second operand
  3691. * @returns the distance
  3692. */
  3693. Vector3.Distance = function (value1, value2) {
  3694. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3695. };
  3696. /**
  3697. * Returns the squared distance between the vectors "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the squared distance
  3701. */
  3702. Vector3.DistanceSquared = function (value1, value2) {
  3703. var x = value1.x - value2.x;
  3704. var y = value1.y - value2.y;
  3705. var z = value1.z - value2.z;
  3706. return (x * x) + (y * y) + (z * z);
  3707. };
  3708. /**
  3709. * Returns a new Vector3 located at the center between "value1" and "value2"
  3710. * @param value1 defines the first operand
  3711. * @param value2 defines the second operand
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Center = function (value1, value2) {
  3715. var center = value1.add(value2);
  3716. center.scaleInPlace(0.5);
  3717. return center;
  3718. };
  3719. /**
  3720. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3721. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3722. * to something in order to rotate it from its local system to the given target system
  3723. * Note: axis1, axis2 and axis3 are normalized during this operation
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @returns a new Vector3
  3728. */
  3729. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3730. var rotation = Vector3.Zero();
  3731. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3732. return rotation;
  3733. };
  3734. /**
  3735. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3736. * @param axis1 defines the first axis
  3737. * @param axis2 defines the second axis
  3738. * @param axis3 defines the third axis
  3739. * @param ref defines the Vector3 where to store the result
  3740. */
  3741. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3742. var quat = MathTmp.Quaternion[0];
  3743. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3744. quat.toEulerAnglesToRef(ref);
  3745. };
  3746. return Vector3;
  3747. }());
  3748. BABYLON.Vector3 = Vector3;
  3749. //Vector4 class created for EulerAngle class conversion to Quaternion
  3750. var Vector4 = /** @class */ (function () {
  3751. /**
  3752. * Creates a Vector4 object from the given floats.
  3753. */
  3754. function Vector4(x, y, z, w) {
  3755. this.x = x;
  3756. this.y = y;
  3757. this.z = z;
  3758. this.w = w;
  3759. }
  3760. /**
  3761. * Returns the string with the Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.toString = function () {
  3764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3765. };
  3766. /**
  3767. * Returns the string "Vector4".
  3768. */
  3769. Vector4.prototype.getClassName = function () {
  3770. return "Vector4";
  3771. };
  3772. /**
  3773. * Returns the Vector4 hash code.
  3774. */
  3775. Vector4.prototype.getHashCode = function () {
  3776. var hash = this.x || 0;
  3777. hash = (hash * 397) ^ (this.y || 0);
  3778. hash = (hash * 397) ^ (this.z || 0);
  3779. hash = (hash * 397) ^ (this.w || 0);
  3780. return hash;
  3781. };
  3782. // Operators
  3783. /**
  3784. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.asArray = function () {
  3787. var result = new Array();
  3788. this.toArray(result, 0);
  3789. return result;
  3790. };
  3791. /**
  3792. * Populates the given array from the given index with the Vector4 coordinates.
  3793. * Returns the Vector4.
  3794. */
  3795. Vector4.prototype.toArray = function (array, index) {
  3796. if (index === undefined) {
  3797. index = 0;
  3798. }
  3799. array[index] = this.x;
  3800. array[index + 1] = this.y;
  3801. array[index + 2] = this.z;
  3802. array[index + 3] = this.w;
  3803. return this;
  3804. };
  3805. /**
  3806. * Adds the given vector to the current Vector4.
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.addInPlace = function (otherVector) {
  3810. this.x += otherVector.x;
  3811. this.y += otherVector.y;
  3812. this.z += otherVector.z;
  3813. this.w += otherVector.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3818. */
  3819. Vector4.prototype.add = function (otherVector) {
  3820. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3821. };
  3822. /**
  3823. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.addToRef = function (otherVector, result) {
  3827. result.x = this.x + otherVector.x;
  3828. result.y = this.y + otherVector.y;
  3829. result.z = this.z + otherVector.z;
  3830. result.w = this.w + otherVector.w;
  3831. return this;
  3832. };
  3833. /**
  3834. * Subtract in place the given vector from the current Vector4.
  3835. * Returns the updated Vector4.
  3836. */
  3837. Vector4.prototype.subtractInPlace = function (otherVector) {
  3838. this.x -= otherVector.x;
  3839. this.y -= otherVector.y;
  3840. this.z -= otherVector.z;
  3841. this.w -= otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3846. */
  3847. Vector4.prototype.subtract = function (otherVector) {
  3848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3849. };
  3850. /**
  3851. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3852. * Returns the current Vector4.
  3853. */
  3854. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3855. result.x = this.x - otherVector.x;
  3856. result.y = this.y - otherVector.y;
  3857. result.z = this.z - otherVector.z;
  3858. result.w = this.w - otherVector.w;
  3859. return this;
  3860. };
  3861. /**
  3862. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3865. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3866. };
  3867. /**
  3868. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3869. * Returns the current Vector4.
  3870. */
  3871. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3872. result.x = this.x - x;
  3873. result.y = this.y - y;
  3874. result.z = this.z - z;
  3875. result.w = this.w - w;
  3876. return this;
  3877. };
  3878. /**
  3879. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3880. */
  3881. Vector4.prototype.negate = function () {
  3882. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3883. };
  3884. /**
  3885. * Multiplies the current Vector4 coordinates by scale (float).
  3886. * Returns the updated Vector4.
  3887. */
  3888. Vector4.prototype.scaleInPlace = function (scale) {
  3889. this.x *= scale;
  3890. this.y *= scale;
  3891. this.z *= scale;
  3892. this.w *= scale;
  3893. return this;
  3894. };
  3895. /**
  3896. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3897. */
  3898. Vector4.prototype.scale = function (scale) {
  3899. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3900. };
  3901. /**
  3902. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3903. * Returns the current Vector4.
  3904. */
  3905. Vector4.prototype.scaleToRef = function (scale, result) {
  3906. result.x = this.x * scale;
  3907. result.y = this.y * scale;
  3908. result.z = this.z * scale;
  3909. result.w = this.w * scale;
  3910. return this;
  3911. };
  3912. /**
  3913. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3914. * @param scale defines the scale factor
  3915. * @param result defines the Vector4 object where to store the result
  3916. * @returns the unmodified current Vector4
  3917. */
  3918. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3919. result.x += this.x * scale;
  3920. result.y += this.y * scale;
  3921. result.z += this.z * scale;
  3922. result.w += this.w * scale;
  3923. return this;
  3924. };
  3925. /**
  3926. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3927. */
  3928. Vector4.prototype.equals = function (otherVector) {
  3929. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3930. };
  3931. /**
  3932. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3933. */
  3934. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3935. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3936. return otherVector
  3937. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3938. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3939. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3940. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3941. };
  3942. /**
  3943. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3946. return this.x === x && this.y === y && this.z === z && this.w === w;
  3947. };
  3948. /**
  3949. * Multiplies in place the current Vector4 by the given one.
  3950. * Returns the updated Vector4.
  3951. */
  3952. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3953. this.x *= otherVector.x;
  3954. this.y *= otherVector.y;
  3955. this.z *= otherVector.z;
  3956. this.w *= otherVector.w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3961. */
  3962. Vector4.prototype.multiply = function (otherVector) {
  3963. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3964. };
  3965. /**
  3966. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3967. * Returns the current Vector4.
  3968. */
  3969. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3970. result.x = this.x * otherVector.x;
  3971. result.y = this.y * otherVector.y;
  3972. result.z = this.z * otherVector.z;
  3973. result.w = this.w * otherVector.w;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3978. */
  3979. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3980. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3984. */
  3985. Vector4.prototype.divide = function (otherVector) {
  3986. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3987. };
  3988. /**
  3989. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3990. * Returns the current Vector4.
  3991. */
  3992. Vector4.prototype.divideToRef = function (otherVector, result) {
  3993. result.x = this.x / otherVector.x;
  3994. result.y = this.y / otherVector.y;
  3995. result.z = this.z / otherVector.z;
  3996. result.w = this.w / otherVector.w;
  3997. return this;
  3998. };
  3999. /**
  4000. * Divides the current Vector3 coordinates by the given ones.
  4001. * @returns the updated Vector3.
  4002. */
  4003. Vector4.prototype.divideInPlace = function (otherVector) {
  4004. return this.divideToRef(otherVector, this);
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.minimizeInPlace = function (other) {
  4012. if (other.x < this.x)
  4013. this.x = other.x;
  4014. if (other.y < this.y)
  4015. this.y = other.y;
  4016. if (other.z < this.z)
  4017. this.z = other.z;
  4018. if (other.w < this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4024. * @param other defines the second operand
  4025. * @returns the current updated Vector4
  4026. */
  4027. Vector4.prototype.maximizeInPlace = function (other) {
  4028. if (other.x > this.x)
  4029. this.x = other.x;
  4030. if (other.y > this.y)
  4031. this.y = other.y;
  4032. if (other.z > this.z)
  4033. this.z = other.z;
  4034. if (other.w > this.w)
  4035. this.w = other.w;
  4036. return this;
  4037. };
  4038. // Properties
  4039. /**
  4040. * Returns the Vector4 length (float).
  4041. */
  4042. Vector4.prototype.length = function () {
  4043. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4044. };
  4045. /**
  4046. * Returns the Vector4 squared length (float).
  4047. */
  4048. Vector4.prototype.lengthSquared = function () {
  4049. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4050. };
  4051. // Methods
  4052. /**
  4053. * Normalizes in place the Vector4.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.normalize = function () {
  4057. var len = this.length();
  4058. if (len === 0)
  4059. return this;
  4060. var num = 1.0 / len;
  4061. this.x *= num;
  4062. this.y *= num;
  4063. this.z *= num;
  4064. this.w *= num;
  4065. return this;
  4066. };
  4067. /**
  4068. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4069. */
  4070. Vector4.prototype.toVector3 = function () {
  4071. return new Vector3(this.x, this.y, this.z);
  4072. };
  4073. /**
  4074. * Returns a new Vector4 copied from the current one.
  4075. */
  4076. Vector4.prototype.clone = function () {
  4077. return new Vector4(this.x, this.y, this.z, this.w);
  4078. };
  4079. /**
  4080. * Updates the current Vector4 with the given one coordinates.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.copyFrom = function (source) {
  4084. this.x = source.x;
  4085. this.y = source.y;
  4086. this.z = source.z;
  4087. this.w = source.w;
  4088. return this;
  4089. };
  4090. /**
  4091. * Updates the current Vector4 coordinates with the given floats.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4095. this.x = x;
  4096. this.y = y;
  4097. this.z = z;
  4098. this.w = w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.set = function (x, y, z, w) {
  4106. return this.copyFromFloats(x, y, z, w);
  4107. };
  4108. // Statics
  4109. /**
  4110. * Returns a new Vector4 set from the starting index of the given array.
  4111. */
  4112. Vector4.FromArray = function (array, offset) {
  4113. if (!offset) {
  4114. offset = 0;
  4115. }
  4116. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" from the starting index of the given array.
  4120. */
  4121. Vector4.FromArrayToRef = function (array, offset, result) {
  4122. result.x = array[offset];
  4123. result.y = array[offset + 1];
  4124. result.z = array[offset + 2];
  4125. result.w = array[offset + 3];
  4126. };
  4127. /**
  4128. * Updates the given vector "result" from the starting index of the given Float32Array.
  4129. */
  4130. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4131. Vector4.FromArrayToRef(array, offset, result);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" coordinates from the given floats.
  4135. */
  4136. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4137. result.x = x;
  4138. result.y = y;
  4139. result.z = z;
  4140. result.w = w;
  4141. };
  4142. /**
  4143. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4144. */
  4145. Vector4.Zero = function () {
  4146. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4147. };
  4148. /**
  4149. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4150. */
  4151. Vector4.One = function () {
  4152. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4153. };
  4154. /**
  4155. * Returns a new normalized Vector4 from the given one.
  4156. */
  4157. Vector4.Normalize = function (vector) {
  4158. var result = Vector4.Zero();
  4159. Vector4.NormalizeToRef(vector, result);
  4160. return result;
  4161. };
  4162. /**
  4163. * Updates the given vector "result" from the normalization of the given one.
  4164. */
  4165. Vector4.NormalizeToRef = function (vector, result) {
  4166. result.copyFrom(vector);
  4167. result.normalize();
  4168. };
  4169. Vector4.Minimize = function (left, right) {
  4170. var min = left.clone();
  4171. min.minimizeInPlace(right);
  4172. return min;
  4173. };
  4174. Vector4.Maximize = function (left, right) {
  4175. var max = left.clone();
  4176. max.maximizeInPlace(right);
  4177. return max;
  4178. };
  4179. /**
  4180. * Returns the distance (float) between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Distance = function (value1, value2) {
  4183. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4184. };
  4185. /**
  4186. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4187. */
  4188. Vector4.DistanceSquared = function (value1, value2) {
  4189. var x = value1.x - value2.x;
  4190. var y = value1.y - value2.y;
  4191. var z = value1.z - value2.z;
  4192. var w = value1.w - value2.w;
  4193. return (x * x) + (y * y) + (z * z) + (w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4197. */
  4198. Vector4.Center = function (value1, value2) {
  4199. var center = value1.add(value2);
  4200. center.scaleInPlace(0.5);
  4201. return center;
  4202. };
  4203. /**
  4204. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4205. * This methods computes transformed normalized direction vectors only.
  4206. */
  4207. Vector4.TransformNormal = function (vector, transformation) {
  4208. var result = Vector4.Zero();
  4209. Vector4.TransformNormalToRef(vector, transformation, result);
  4210. return result;
  4211. };
  4212. /**
  4213. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4214. * This methods computes transformed normalized direction vectors only.
  4215. */
  4216. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4217. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4218. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4219. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4220. result.x = x;
  4221. result.y = y;
  4222. result.z = z;
  4223. result.w = vector.w;
  4224. };
  4225. /**
  4226. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4227. * This methods computes transformed normalized direction vectors only.
  4228. */
  4229. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4230. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4231. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4232. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4233. result.w = w;
  4234. };
  4235. return Vector4;
  4236. }());
  4237. BABYLON.Vector4 = Vector4;
  4238. var Size = /** @class */ (function () {
  4239. /**
  4240. * Creates a Size object from the given width and height (floats).
  4241. */
  4242. function Size(width, height) {
  4243. this.width = width;
  4244. this.height = height;
  4245. }
  4246. // Returns a string with the Size width and height.
  4247. Size.prototype.toString = function () {
  4248. return "{W: " + this.width + ", H: " + this.height + "}";
  4249. };
  4250. /**
  4251. * Returns the string "Size"
  4252. */
  4253. Size.prototype.getClassName = function () {
  4254. return "Size";
  4255. };
  4256. /**
  4257. * Returns the Size hash code.
  4258. */
  4259. Size.prototype.getHashCode = function () {
  4260. var hash = this.width || 0;
  4261. hash = (hash * 397) ^ (this.height || 0);
  4262. return hash;
  4263. };
  4264. /**
  4265. * Updates the current size from the given one.
  4266. * Returns the updated Size.
  4267. */
  4268. Size.prototype.copyFrom = function (src) {
  4269. this.width = src.width;
  4270. this.height = src.height;
  4271. };
  4272. /**
  4273. * Updates in place the current Size from the given floats.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFromFloats = function (width, height) {
  4277. this.width = width;
  4278. this.height = height;
  4279. return this;
  4280. };
  4281. /**
  4282. * Updates in place the current Size from the given floats.
  4283. * Returns the updated Size.
  4284. */
  4285. Size.prototype.set = function (width, height) {
  4286. return this.copyFromFloats(width, height);
  4287. };
  4288. /**
  4289. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4290. */
  4291. Size.prototype.multiplyByFloats = function (w, h) {
  4292. return new Size(this.width * w, this.height * h);
  4293. };
  4294. /**
  4295. * Returns a new Size copied from the given one.
  4296. */
  4297. Size.prototype.clone = function () {
  4298. return new Size(this.width, this.height);
  4299. };
  4300. /**
  4301. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4302. */
  4303. Size.prototype.equals = function (other) {
  4304. if (!other) {
  4305. return false;
  4306. }
  4307. return (this.width === other.width) && (this.height === other.height);
  4308. };
  4309. Object.defineProperty(Size.prototype, "surface", {
  4310. /**
  4311. * Returns the surface of the Size : width * height (float).
  4312. */
  4313. get: function () {
  4314. return this.width * this.height;
  4315. },
  4316. enumerable: true,
  4317. configurable: true
  4318. });
  4319. /**
  4320. * Returns a new Size set to (0.0, 0.0)
  4321. */
  4322. Size.Zero = function () {
  4323. return new Size(0.0, 0.0);
  4324. };
  4325. /**
  4326. * Returns a new Size set as the addition result of the current Size and the given one.
  4327. */
  4328. Size.prototype.add = function (otherSize) {
  4329. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4330. return r;
  4331. };
  4332. /**
  4333. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4334. */
  4335. Size.prototype.subtract = function (otherSize) {
  4336. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4337. return r;
  4338. };
  4339. /**
  4340. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4341. */
  4342. Size.Lerp = function (start, end, amount) {
  4343. var w = start.width + ((end.width - start.width) * amount);
  4344. var h = start.height + ((end.height - start.height) * amount);
  4345. return new Size(w, h);
  4346. };
  4347. return Size;
  4348. }());
  4349. BABYLON.Size = Size;
  4350. /**
  4351. * Class used to store quaternion data
  4352. * @see https://en.wikipedia.org/wiki/Quaternion
  4353. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4354. */
  4355. var Quaternion = /** @class */ (function () {
  4356. /**
  4357. * Creates a new Quaternion from the given floats
  4358. * @param x defines the first component (0 by default)
  4359. * @param y defines the second component (0 by default)
  4360. * @param z defines the third component (0 by default)
  4361. * @param w defines the fourth component (1.0 by default)
  4362. */
  4363. function Quaternion(
  4364. /** defines the first component (0 by default) */
  4365. x,
  4366. /** defines the second component (0 by default) */
  4367. y,
  4368. /** defines the third component (0 by default) */
  4369. z,
  4370. /** defines the fourth component (1.0 by default) */
  4371. w) {
  4372. if (x === void 0) { x = 0.0; }
  4373. if (y === void 0) { y = 0.0; }
  4374. if (z === void 0) { z = 0.0; }
  4375. if (w === void 0) { w = 1.0; }
  4376. this.x = x;
  4377. this.y = y;
  4378. this.z = z;
  4379. this.w = w;
  4380. }
  4381. /**
  4382. * Gets a string representation for the current quaternion
  4383. * @returns a string with the Quaternion coordinates
  4384. */
  4385. Quaternion.prototype.toString = function () {
  4386. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4387. };
  4388. /**
  4389. * Gets the class name of the quaternion
  4390. * @returns the string "Quaternion"
  4391. */
  4392. Quaternion.prototype.getClassName = function () {
  4393. return "Quaternion";
  4394. };
  4395. /**
  4396. * Gets a hash code for this quaternion
  4397. * @returns the quaternion hash code
  4398. */
  4399. Quaternion.prototype.getHashCode = function () {
  4400. var hash = this.x || 0;
  4401. hash = (hash * 397) ^ (this.y || 0);
  4402. hash = (hash * 397) ^ (this.z || 0);
  4403. hash = (hash * 397) ^ (this.w || 0);
  4404. return hash;
  4405. };
  4406. /**
  4407. * Copy the quaternion to an array
  4408. * @returns a new array populated with 4 elements from the quaternion coordinates
  4409. */
  4410. Quaternion.prototype.asArray = function () {
  4411. return [this.x, this.y, this.z, this.w];
  4412. };
  4413. /**
  4414. * Check if two quaternions are equals
  4415. * @param otherQuaternion defines the second operand
  4416. * @return true if the current quaternion and the given one coordinates are strictly equals
  4417. */
  4418. Quaternion.prototype.equals = function (otherQuaternion) {
  4419. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4420. };
  4421. /**
  4422. * Clone the current quaternion
  4423. * @returns a new quaternion copied from the current one
  4424. */
  4425. Quaternion.prototype.clone = function () {
  4426. return new Quaternion(this.x, this.y, this.z, this.w);
  4427. };
  4428. /**
  4429. * Copy a quaternion to the current one
  4430. * @param other defines the other quaternion
  4431. * @returns the updated current quaternion
  4432. */
  4433. Quaternion.prototype.copyFrom = function (other) {
  4434. this.x = other.x;
  4435. this.y = other.y;
  4436. this.z = other.z;
  4437. this.w = other.w;
  4438. return this;
  4439. };
  4440. /**
  4441. * Updates the current quaternion with the given float coordinates
  4442. * @param x defines the x coordinate
  4443. * @param y defines the y coordinate
  4444. * @param z defines the z coordinate
  4445. * @param w defines the w coordinate
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4449. this.x = x;
  4450. this.y = y;
  4451. this.z = z;
  4452. this.w = w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion from the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.set = function (x, y, z, w) {
  4464. return this.copyFromFloats(x, y, z, w);
  4465. };
  4466. /**
  4467. * Adds two quaternions
  4468. * @param other defines the second operand
  4469. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4470. */
  4471. Quaternion.prototype.add = function (other) {
  4472. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4473. };
  4474. /**
  4475. * Add a quaternion to the current one
  4476. * @param other defines the quaternion to add
  4477. * @returns the current quaternion
  4478. */
  4479. Quaternion.prototype.addInPlace = function (other) {
  4480. this.x += other.x;
  4481. this.y += other.y;
  4482. this.z += other.z;
  4483. this.w += other.w;
  4484. return this;
  4485. };
  4486. /**
  4487. * Subtract two quaternions
  4488. * @param other defines the second operand
  4489. * @returns a new quaternion as the subtraction result of the given one from the current one
  4490. */
  4491. Quaternion.prototype.subtract = function (other) {
  4492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4493. };
  4494. /**
  4495. * Multiplies the current quaternion by a scale factor
  4496. * @param value defines the scale factor
  4497. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4498. */
  4499. Quaternion.prototype.scale = function (value) {
  4500. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4501. };
  4502. /**
  4503. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4504. * @param scale defines the scale factor
  4505. * @param result defines the Quaternion object where to store the result
  4506. * @returns the unmodified current quaternion
  4507. */
  4508. Quaternion.prototype.scaleToRef = function (scale, result) {
  4509. result.x = this.x * scale;
  4510. result.y = this.y * scale;
  4511. result.z = this.z * scale;
  4512. result.w = this.w * scale;
  4513. return this;
  4514. };
  4515. /**
  4516. * Multiplies in place the current quaternion by a scale factor
  4517. * @param value defines the scale factor
  4518. * @returns the current modified quaternion
  4519. */
  4520. Quaternion.prototype.scaleInPlace = function (value) {
  4521. this.x *= value;
  4522. this.y *= value;
  4523. this.z *= value;
  4524. this.w *= value;
  4525. return this;
  4526. };
  4527. /**
  4528. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4529. * @param scale defines the scale factor
  4530. * @param result defines the Quaternion object where to store the result
  4531. * @returns the unmodified current quaternion
  4532. */
  4533. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4534. result.x += this.x * scale;
  4535. result.y += this.y * scale;
  4536. result.z += this.z * scale;
  4537. result.w += this.w * scale;
  4538. return this;
  4539. };
  4540. /**
  4541. * Multiplies two quaternions
  4542. * @param q1 defines the second operand
  4543. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4544. */
  4545. Quaternion.prototype.multiply = function (q1) {
  4546. var result = new Quaternion(0, 0, 0, 1.0);
  4547. this.multiplyToRef(q1, result);
  4548. return result;
  4549. };
  4550. /**
  4551. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4552. * @param q1 defines the second operand
  4553. * @param result defines the target quaternion
  4554. * @returns the current quaternion
  4555. */
  4556. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4557. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4558. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4559. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4560. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4561. result.copyFromFloats(x, y, z, w);
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4566. * @param q1 defines the second operand
  4567. * @returns the currentupdated quaternion
  4568. */
  4569. Quaternion.prototype.multiplyInPlace = function (q1) {
  4570. this.multiplyToRef(q1, this);
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4575. * @param ref defines the target quaternion
  4576. * @returns the current quaternion
  4577. */
  4578. Quaternion.prototype.conjugateToRef = function (ref) {
  4579. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4580. return this;
  4581. };
  4582. /**
  4583. * Conjugates in place (1-q) the current quaternion
  4584. * @returns the current updated quaternion
  4585. */
  4586. Quaternion.prototype.conjugateInPlace = function () {
  4587. this.x *= -1;
  4588. this.y *= -1;
  4589. this.z *= -1;
  4590. return this;
  4591. };
  4592. /**
  4593. * Conjugates in place (1-q) the current quaternion
  4594. * @returns a new quaternion
  4595. */
  4596. Quaternion.prototype.conjugate = function () {
  4597. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4598. return result;
  4599. };
  4600. /**
  4601. * Gets length of current quaternion
  4602. * @returns the quaternion length (float)
  4603. */
  4604. Quaternion.prototype.length = function () {
  4605. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4606. };
  4607. /**
  4608. * Normalize in place the current quaternion
  4609. * @returns the current updated quaternion
  4610. */
  4611. Quaternion.prototype.normalize = function () {
  4612. var length = 1.0 / this.length();
  4613. this.x *= length;
  4614. this.y *= length;
  4615. this.z *= length;
  4616. this.w *= length;
  4617. return this;
  4618. };
  4619. /**
  4620. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns a new Vector3 containing the Euler angles
  4623. */
  4624. Quaternion.prototype.toEulerAngles = function (order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var result = Vector3.Zero();
  4627. this.toEulerAnglesToRef(result, order);
  4628. return result;
  4629. };
  4630. /**
  4631. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4632. * @param result defines the vector which will be filled with the Euler angles
  4633. * @param order is a reserved parameter and is ignore for now
  4634. * @returns the current unchanged quaternion
  4635. */
  4636. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4637. if (order === void 0) { order = "YZX"; }
  4638. var qz = this.z;
  4639. var qx = this.x;
  4640. var qy = this.y;
  4641. var qw = this.w;
  4642. var sqw = qw * qw;
  4643. var sqz = qz * qz;
  4644. var sqx = qx * qx;
  4645. var sqy = qy * qy;
  4646. var zAxisY = qy * qz - qx * qw;
  4647. var limit = .4999999;
  4648. if (zAxisY < -limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else if (zAxisY > limit) {
  4654. result.y = 2 * Math.atan2(qy, qw);
  4655. result.x = -Math.PI / 2;
  4656. result.z = 0;
  4657. }
  4658. else {
  4659. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4660. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4661. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4662. }
  4663. return this;
  4664. };
  4665. /**
  4666. * Updates the given rotation matrix with the current quaternion values
  4667. * @param result defines the target matrix
  4668. * @returns the current unchanged quaternion
  4669. */
  4670. Quaternion.prototype.toRotationMatrix = function (result) {
  4671. var xx = this.x * this.x;
  4672. var yy = this.y * this.y;
  4673. var zz = this.z * this.z;
  4674. var xy = this.x * this.y;
  4675. var zw = this.z * this.w;
  4676. var zx = this.z * this.x;
  4677. var yw = this.y * this.w;
  4678. var yz = this.y * this.z;
  4679. var xw = this.x * this.w;
  4680. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4681. result.m[1] = 2.0 * (xy + zw);
  4682. result.m[2] = 2.0 * (zx - yw);
  4683. result.m[3] = 0;
  4684. result.m[4] = 2.0 * (xy - zw);
  4685. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4686. result.m[6] = 2.0 * (yz + xw);
  4687. result.m[7] = 0;
  4688. result.m[8] = 2.0 * (zx + yw);
  4689. result.m[9] = 2.0 * (yz - xw);
  4690. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4691. result.m[11] = 0;
  4692. result.m[12] = 0;
  4693. result.m[13] = 0;
  4694. result.m[14] = 0;
  4695. result.m[15] = 1.0;
  4696. result._markAsUpdated();
  4697. return this;
  4698. };
  4699. /**
  4700. * Updates the current quaternion from the given rotation matrix values
  4701. * @param matrix defines the source matrix
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4705. Quaternion.FromRotationMatrixToRef(matrix, this);
  4706. return this;
  4707. };
  4708. // Statics
  4709. /**
  4710. * Creates a new quaternion from a rotation matrix
  4711. * @param matrix defines the source matrix
  4712. * @returns a new quaternion created from the given rotation matrix values
  4713. */
  4714. Quaternion.FromRotationMatrix = function (matrix) {
  4715. var result = new Quaternion();
  4716. Quaternion.FromRotationMatrixToRef(matrix, result);
  4717. return result;
  4718. };
  4719. /**
  4720. * Updates the given quaternion with the given rotation matrix values
  4721. * @param matrix defines the source matrix
  4722. * @param result defines the target quaternion
  4723. */
  4724. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4725. var data = matrix.m;
  4726. var m11 = data[0], m12 = data[4], m13 = data[8];
  4727. var m21 = data[1], m22 = data[5], m23 = data[9];
  4728. var m31 = data[2], m32 = data[6], m33 = data[10];
  4729. var trace = m11 + m22 + m33;
  4730. var s;
  4731. if (trace > 0) {
  4732. s = 0.5 / Math.sqrt(trace + 1.0);
  4733. result.w = 0.25 / s;
  4734. result.x = (m32 - m23) * s;
  4735. result.y = (m13 - m31) * s;
  4736. result.z = (m21 - m12) * s;
  4737. }
  4738. else if (m11 > m22 && m11 > m33) {
  4739. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4740. result.w = (m32 - m23) / s;
  4741. result.x = 0.25 * s;
  4742. result.y = (m12 + m21) / s;
  4743. result.z = (m13 + m31) / s;
  4744. }
  4745. else if (m22 > m33) {
  4746. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4747. result.w = (m13 - m31) / s;
  4748. result.x = (m12 + m21) / s;
  4749. result.y = 0.25 * s;
  4750. result.z = (m23 + m32) / s;
  4751. }
  4752. else {
  4753. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4754. result.w = (m21 - m12) / s;
  4755. result.x = (m13 + m31) / s;
  4756. result.y = (m23 + m32) / s;
  4757. result.z = 0.25 * s;
  4758. }
  4759. };
  4760. /**
  4761. * Returns the dot product (float) between the quaternions "left" and "right"
  4762. * @param left defines the left operand
  4763. * @param right defines the right operand
  4764. * @returns the dot product
  4765. */
  4766. Quaternion.Dot = function (left, right) {
  4767. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4768. };
  4769. /**
  4770. * Checks if the two quaternions are close to each other
  4771. * @param quat0 defines the first quaternion to check
  4772. * @param quat1 defines the second quaternion to check
  4773. * @returns true if the two quaternions are close to each other
  4774. */
  4775. Quaternion.AreClose = function (quat0, quat1) {
  4776. var dot = Quaternion.Dot(quat0, quat1);
  4777. return dot >= 0;
  4778. };
  4779. /**
  4780. * Creates an empty quaternion
  4781. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4782. */
  4783. Quaternion.Zero = function () {
  4784. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4785. };
  4786. /**
  4787. * Inverse a given quaternion
  4788. * @param q defines the source quaternion
  4789. * @returns a new quaternion as the inverted current quaternion
  4790. */
  4791. Quaternion.Inverse = function (q) {
  4792. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4793. };
  4794. /**
  4795. * Creates an identity quaternion
  4796. * @returns the identity quaternion
  4797. */
  4798. Quaternion.Identity = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4800. };
  4801. /**
  4802. * Gets a boolean indicating if the given quaternion is identity
  4803. * @param quaternion defines the quaternion to check
  4804. * @returns true if the quaternion is identity
  4805. */
  4806. Quaternion.IsIdentity = function (quaternion) {
  4807. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4808. };
  4809. /**
  4810. * Creates a quaternion from a rotation around an axis
  4811. * @param axis defines the axis to use
  4812. * @param angle defines the angle to use
  4813. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4814. */
  4815. Quaternion.RotationAxis = function (axis, angle) {
  4816. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4817. };
  4818. /**
  4819. * Creates a rotation around an axis and stores it into the given quaternion
  4820. * @param axis defines the axis to use
  4821. * @param angle defines the angle to use
  4822. * @param result defines the target quaternion
  4823. * @returns the target quaternion
  4824. */
  4825. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4826. var sin = Math.sin(angle / 2);
  4827. axis.normalize();
  4828. result.w = Math.cos(angle / 2);
  4829. result.x = axis.x * sin;
  4830. result.y = axis.y * sin;
  4831. result.z = axis.z * sin;
  4832. return result;
  4833. };
  4834. /**
  4835. * Creates a new quaternion from data stored into an array
  4836. * @param array defines the data source
  4837. * @param offset defines the offset in the source array where the data starts
  4838. * @returns a new quaternion
  4839. */
  4840. Quaternion.FromArray = function (array, offset) {
  4841. if (!offset) {
  4842. offset = 0;
  4843. }
  4844. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4845. };
  4846. /**
  4847. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @returns the new quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4854. var q = new Quaternion();
  4855. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4856. return q;
  4857. };
  4858. /**
  4859. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4860. * @param yaw defines the rotation around Y axis
  4861. * @param pitch defines the rotation around X axis
  4862. * @param roll defines the rotation around Z axis
  4863. * @param result defines the target quaternion
  4864. */
  4865. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4866. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4867. var halfRoll = roll * 0.5;
  4868. var halfPitch = pitch * 0.5;
  4869. var halfYaw = yaw * 0.5;
  4870. var sinRoll = Math.sin(halfRoll);
  4871. var cosRoll = Math.cos(halfRoll);
  4872. var sinPitch = Math.sin(halfPitch);
  4873. var cosPitch = Math.cos(halfPitch);
  4874. var sinYaw = Math.sin(halfYaw);
  4875. var cosYaw = Math.cos(halfYaw);
  4876. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4877. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4878. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4879. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @returns the new quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4889. var result = new Quaternion();
  4890. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4891. return result;
  4892. };
  4893. /**
  4894. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4895. * @param alpha defines the rotation around first axis
  4896. * @param beta defines the rotation around second axis
  4897. * @param gamma defines the rotation around third axis
  4898. * @param result defines the target quaternion
  4899. */
  4900. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4901. // Produces a quaternion from Euler angles in the z-x-z orientation
  4902. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4903. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4904. var halfBeta = beta * 0.5;
  4905. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4906. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4907. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4908. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4909. };
  4910. /**
  4911. * Creates a new quaternion containing the rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation)
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @returns the new quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4918. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4919. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4920. return quat;
  4921. };
  4922. /**
  4923. * Creates a rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system (axis1, axis2 and axis3 are normalized during this operation) and stores it in the target quaternion
  4924. * @param axis1 defines the first axis
  4925. * @param axis2 defines the second axis
  4926. * @param axis3 defines the third axis
  4927. * @param ref defines the target quaternion
  4928. */
  4929. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4930. var rotMat = MathTmp.Matrix[0];
  4931. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4932. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @returns the new interpolated quaternion
  4940. */
  4941. Quaternion.Slerp = function (left, right, amount) {
  4942. var result = Quaternion.Identity();
  4943. Quaternion.SlerpToRef(left, right, amount, result);
  4944. return result;
  4945. };
  4946. /**
  4947. * Interpolates between two quaternions and stores it into a target quaternion
  4948. * @param left defines first quaternion
  4949. * @param right defines second quaternion
  4950. * @param amount defines the gradient to use
  4951. * @param result defines the target quaternion
  4952. */
  4953. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4954. var num2;
  4955. var num3;
  4956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4957. var flag = false;
  4958. if (num4 < 0) {
  4959. flag = true;
  4960. num4 = -num4;
  4961. }
  4962. if (num4 > 0.999999) {
  4963. num3 = 1 - amount;
  4964. num2 = flag ? -amount : amount;
  4965. }
  4966. else {
  4967. var num5 = Math.acos(num4);
  4968. var num6 = (1.0 / Math.sin(num5));
  4969. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4970. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4971. }
  4972. result.x = (num3 * left.x) + (num2 * right.x);
  4973. result.y = (num3 * left.y) + (num2 * right.y);
  4974. result.z = (num3 * left.z) + (num2 * right.z);
  4975. result.w = (num3 * left.w) + (num2 * right.w);
  4976. };
  4977. /**
  4978. * Interpolate between two quaternions using Hermite interpolation
  4979. * @param value1 defines first quaternion
  4980. * @param tangent1 defines the incoming tangent
  4981. * @param value2 defines second quaternion
  4982. * @param tangent2 defines the outgoing tangent
  4983. * @param amount defines the target quaternion
  4984. * @returns the new interpolated quaternion
  4985. */
  4986. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4987. var squared = amount * amount;
  4988. var cubed = amount * squared;
  4989. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4990. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4991. var part3 = (cubed - (2.0 * squared)) + amount;
  4992. var part4 = cubed - squared;
  4993. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4994. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4995. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4996. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4997. return new Quaternion(x, y, z, w);
  4998. };
  4999. return Quaternion;
  5000. }());
  5001. BABYLON.Quaternion = Quaternion;
  5002. /**
  5003. * Class used to store matrix data (4x4)
  5004. */
  5005. var Matrix = /** @class */ (function () {
  5006. /**
  5007. * Creates an empty matrix (filled with zeros)
  5008. */
  5009. function Matrix() {
  5010. this._isIdentity = false;
  5011. this._isIdentityDirty = true;
  5012. /**
  5013. * Gets or sets the internal data of the matrix
  5014. */
  5015. this.m = new Float32Array(16);
  5016. this._markAsUpdated();
  5017. }
  5018. /** @hidden */
  5019. Matrix.prototype._markAsUpdated = function () {
  5020. this.updateFlag = Matrix._updateFlagSeed++;
  5021. this._isIdentityDirty = true;
  5022. };
  5023. // Properties
  5024. /**
  5025. * Check if the current matrix is indentity
  5026. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5027. * @returns true is the matrix is the identity matrix
  5028. */
  5029. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5030. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5031. if (this._isIdentityDirty) {
  5032. this._isIdentityDirty = false;
  5033. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5037. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5038. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5039. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5040. this._isIdentity = false;
  5041. }
  5042. else {
  5043. this._isIdentity = true;
  5044. }
  5045. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5046. this._isIdentity = false;
  5047. }
  5048. }
  5049. return this._isIdentity;
  5050. };
  5051. /**
  5052. * Gets the determinant of the matrix
  5053. * @returns the matrix determinant
  5054. */
  5055. Matrix.prototype.determinant = function () {
  5056. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5057. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5058. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5059. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5060. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5061. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5062. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5063. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5064. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5065. };
  5066. // Methods
  5067. /**
  5068. * Returns the matrix as a Float32Array
  5069. * @returns the matrix underlying array
  5070. */
  5071. Matrix.prototype.toArray = function () {
  5072. return this.m;
  5073. };
  5074. /**
  5075. * Returns the matrix as a Float32Array
  5076. * @returns the matrix underlying array.
  5077. */
  5078. Matrix.prototype.asArray = function () {
  5079. return this.toArray();
  5080. };
  5081. /**
  5082. * Inverts the current matrix in place
  5083. * @returns the current inverted matrix
  5084. */
  5085. Matrix.prototype.invert = function () {
  5086. this.invertToRef(this);
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets all the matrix elements to zero
  5091. * @returns the current matrix
  5092. */
  5093. Matrix.prototype.reset = function () {
  5094. for (var index = 0; index < 16; index++) {
  5095. this.m[index] = 0.0;
  5096. }
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Adds the current matrix with a second one
  5102. * @param other defines the matrix to add
  5103. * @returns a new matrix as the addition of the current matrix and the given one
  5104. */
  5105. Matrix.prototype.add = function (other) {
  5106. var result = new Matrix();
  5107. this.addToRef(other, result);
  5108. return result;
  5109. };
  5110. /**
  5111. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5112. * @param other defines the matrix to add
  5113. * @param result defines the target matrix
  5114. * @returns the current matrix
  5115. */
  5116. Matrix.prototype.addToRef = function (other, result) {
  5117. for (var index = 0; index < 16; index++) {
  5118. result.m[index] = this.m[index] + other.m[index];
  5119. }
  5120. result._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Adds in place the given matrix to the current matrix
  5125. * @param other defines the second operand
  5126. * @returns the current updated matrix
  5127. */
  5128. Matrix.prototype.addToSelf = function (other) {
  5129. for (var index = 0; index < 16; index++) {
  5130. this.m[index] += other.m[index];
  5131. }
  5132. this._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the given matrix to the current inverted Matrix
  5137. * @param other defines the target matrix
  5138. * @returns the unmodified current matrix
  5139. */
  5140. Matrix.prototype.invertToRef = function (other) {
  5141. var l1 = this.m[0];
  5142. var l2 = this.m[1];
  5143. var l3 = this.m[2];
  5144. var l4 = this.m[3];
  5145. var l5 = this.m[4];
  5146. var l6 = this.m[5];
  5147. var l7 = this.m[6];
  5148. var l8 = this.m[7];
  5149. var l9 = this.m[8];
  5150. var l10 = this.m[9];
  5151. var l11 = this.m[10];
  5152. var l12 = this.m[11];
  5153. var l13 = this.m[12];
  5154. var l14 = this.m[13];
  5155. var l15 = this.m[14];
  5156. var l16 = this.m[15];
  5157. var l17 = (l11 * l16) - (l12 * l15);
  5158. var l18 = (l10 * l16) - (l12 * l14);
  5159. var l19 = (l10 * l15) - (l11 * l14);
  5160. var l20 = (l9 * l16) - (l12 * l13);
  5161. var l21 = (l9 * l15) - (l11 * l13);
  5162. var l22 = (l9 * l14) - (l10 * l13);
  5163. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5164. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5165. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5166. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5167. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5168. var l28 = (l7 * l16) - (l8 * l15);
  5169. var l29 = (l6 * l16) - (l8 * l14);
  5170. var l30 = (l6 * l15) - (l7 * l14);
  5171. var l31 = (l5 * l16) - (l8 * l13);
  5172. var l32 = (l5 * l15) - (l7 * l13);
  5173. var l33 = (l5 * l14) - (l6 * l13);
  5174. var l34 = (l7 * l12) - (l8 * l11);
  5175. var l35 = (l6 * l12) - (l8 * l10);
  5176. var l36 = (l6 * l11) - (l7 * l10);
  5177. var l37 = (l5 * l12) - (l8 * l9);
  5178. var l38 = (l5 * l11) - (l7 * l9);
  5179. var l39 = (l5 * l10) - (l6 * l9);
  5180. other.m[0] = l23 * l27;
  5181. other.m[4] = l24 * l27;
  5182. other.m[8] = l25 * l27;
  5183. other.m[12] = l26 * l27;
  5184. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5185. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5186. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5187. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5188. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5189. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5190. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5191. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5192. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5193. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5194. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5195. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5196. other._markAsUpdated();
  5197. return this;
  5198. };
  5199. /**
  5200. * Inserts the translation vector (using 3 floats) in the current matrix
  5201. * @param x defines the 1st component of the translation
  5202. * @param y defines the 2nd component of the translation
  5203. * @param z defines the 3rd component of the translation
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5207. this.m[12] = x;
  5208. this.m[13] = y;
  5209. this.m[14] = z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector in the current matrix
  5215. * @param vector3 defines the translation to insert
  5216. * @returns the current updated matrix
  5217. */
  5218. Matrix.prototype.setTranslation = function (vector3) {
  5219. this.m[12] = vector3.x;
  5220. this.m[13] = vector3.y;
  5221. this.m[14] = vector3.z;
  5222. this._markAsUpdated();
  5223. return this;
  5224. };
  5225. /**
  5226. * Gets the translation value of the current matrix
  5227. * @returns a new Vector3 as the extracted translation from the matrix
  5228. */
  5229. Matrix.prototype.getTranslation = function () {
  5230. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5231. };
  5232. /**
  5233. * Fill a Vector3 with the extracted translation from the matrix
  5234. * @param result defines the Vector3 where to store the translation
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.getTranslationToRef = function (result) {
  5238. result.x = this.m[12];
  5239. result.y = this.m[13];
  5240. result.z = this.m[14];
  5241. return this;
  5242. };
  5243. /**
  5244. * Remove rotation and scaling part from the matrix
  5245. * @returns the updated matrix
  5246. */
  5247. Matrix.prototype.removeRotationAndScaling = function () {
  5248. this.setRowFromFloats(0, 1, 0, 0, 0);
  5249. this.setRowFromFloats(1, 0, 1, 0, 0);
  5250. this.setRowFromFloats(2, 0, 0, 1, 0);
  5251. return this;
  5252. };
  5253. /**
  5254. * Multiply two matrices
  5255. * @param other defines the second operand
  5256. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5257. */
  5258. Matrix.prototype.multiply = function (other) {
  5259. var result = new Matrix();
  5260. this.multiplyToRef(other, result);
  5261. return result;
  5262. };
  5263. /**
  5264. * Copy the current matrix from the given one
  5265. * @param other defines the source matrix
  5266. * @returns the current updated matrix
  5267. */
  5268. Matrix.prototype.copyFrom = function (other) {
  5269. for (var index = 0; index < 16; index++) {
  5270. this.m[index] = other.m[index];
  5271. }
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Populates the given array from the starting index with the current matrix values
  5277. * @param array defines the target array
  5278. * @param offset defines the offset in the target array where to start storing values
  5279. * @returns the current matrix
  5280. */
  5281. Matrix.prototype.copyToArray = function (array, offset) {
  5282. if (offset === void 0) { offset = 0; }
  5283. for (var index = 0; index < 16; index++) {
  5284. array[offset + index] = this.m[index];
  5285. }
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the matrix where to store the multiplication
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToRef = function (other, result) {
  5295. this.multiplyToArray(other, result.m, 0);
  5296. result._markAsUpdated();
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the array where to store the multiplication
  5303. * @param offset defines the offset in the target array where to start storing values
  5304. * @returns the current matrix
  5305. */
  5306. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5307. var tm0 = this.m[0];
  5308. var tm1 = this.m[1];
  5309. var tm2 = this.m[2];
  5310. var tm3 = this.m[3];
  5311. var tm4 = this.m[4];
  5312. var tm5 = this.m[5];
  5313. var tm6 = this.m[6];
  5314. var tm7 = this.m[7];
  5315. var tm8 = this.m[8];
  5316. var tm9 = this.m[9];
  5317. var tm10 = this.m[10];
  5318. var tm11 = this.m[11];
  5319. var tm12 = this.m[12];
  5320. var tm13 = this.m[13];
  5321. var tm14 = this.m[14];
  5322. var tm15 = this.m[15];
  5323. var om0 = other.m[0];
  5324. var om1 = other.m[1];
  5325. var om2 = other.m[2];
  5326. var om3 = other.m[3];
  5327. var om4 = other.m[4];
  5328. var om5 = other.m[5];
  5329. var om6 = other.m[6];
  5330. var om7 = other.m[7];
  5331. var om8 = other.m[8];
  5332. var om9 = other.m[9];
  5333. var om10 = other.m[10];
  5334. var om11 = other.m[11];
  5335. var om12 = other.m[12];
  5336. var om13 = other.m[13];
  5337. var om14 = other.m[14];
  5338. var om15 = other.m[15];
  5339. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5340. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5341. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5342. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5343. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5344. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5345. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5346. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5347. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5348. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5349. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5350. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5351. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5352. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5353. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5354. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5355. return this;
  5356. };
  5357. /**
  5358. * Check equality between this matrix and a second one
  5359. * @param value defines the second matrix to compare
  5360. * @returns true is the current matrix and the given one values are strictly equal
  5361. */
  5362. Matrix.prototype.equals = function (value) {
  5363. return value &&
  5364. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5365. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5366. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5367. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5368. };
  5369. /**
  5370. * Clone the current matrix
  5371. * @returns a new matrix from the current matrix
  5372. */
  5373. Matrix.prototype.clone = function () {
  5374. 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]);
  5375. };
  5376. /**
  5377. * Returns the name of the current matrix class
  5378. * @returns the string "Matrix"
  5379. */
  5380. Matrix.prototype.getClassName = function () {
  5381. return "Matrix";
  5382. };
  5383. /**
  5384. * Gets the hash code of the current matrix
  5385. * @returns the hash code
  5386. */
  5387. Matrix.prototype.getHashCode = function () {
  5388. var hash = this.m[0] || 0;
  5389. for (var i = 1; i < 16; i++) {
  5390. hash = (hash * 397) ^ (this.m[i] || 0);
  5391. }
  5392. return hash;
  5393. };
  5394. /**
  5395. * Decomposes the current Matrix into a translation, rotation and scaling components
  5396. * @param scale defines the scale vector3 given as a reference to update
  5397. * @param rotation defines the rotation quaternion given as a reference to update
  5398. * @param translation defines the translation vector3 given as a reference to update
  5399. * @returns true if operation was successful
  5400. */
  5401. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5402. if (translation) {
  5403. translation.x = this.m[12];
  5404. translation.y = this.m[13];
  5405. translation.z = this.m[14];
  5406. }
  5407. scale = scale || MathTmp.Vector3[0];
  5408. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5409. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5410. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5411. if (this.determinant() <= 0) {
  5412. scale.y *= -1;
  5413. }
  5414. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5415. if (rotation) {
  5416. rotation.x = 0;
  5417. rotation.y = 0;
  5418. rotation.z = 0;
  5419. rotation.w = 1;
  5420. }
  5421. return false;
  5422. }
  5423. if (rotation) {
  5424. 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]);
  5425. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5426. }
  5427. return true;
  5428. };
  5429. /**
  5430. * Gets specific row of the matrix
  5431. * @param index defines the number of the row to get
  5432. * @returns the index-th row of the current matrix as a new Vector4
  5433. */
  5434. Matrix.prototype.getRow = function (index) {
  5435. if (index < 0 || index > 3) {
  5436. return null;
  5437. }
  5438. var i = index * 4;
  5439. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5440. };
  5441. /**
  5442. * Sets the index-th row of the current matrix to the vector4 values
  5443. * @param index defines the number of the row to set
  5444. * @param row defines the target vector4
  5445. * @returns the updated current matrix
  5446. */
  5447. Matrix.prototype.setRow = function (index, row) {
  5448. if (index < 0 || index > 3) {
  5449. return this;
  5450. }
  5451. var i = index * 4;
  5452. this.m[i + 0] = row.x;
  5453. this.m[i + 1] = row.y;
  5454. this.m[i + 2] = row.z;
  5455. this.m[i + 3] = row.w;
  5456. this._markAsUpdated();
  5457. return this;
  5458. };
  5459. /**
  5460. * Compute the transpose of the matrix
  5461. * @returns the new transposed matrix
  5462. */
  5463. Matrix.prototype.transpose = function () {
  5464. return Matrix.Transpose(this);
  5465. };
  5466. /**
  5467. * Compute the transpose of the matrix and store it in a given matrix
  5468. * @param result defines the target matrix
  5469. * @returns the current matrix
  5470. */
  5471. Matrix.prototype.transposeToRef = function (result) {
  5472. Matrix.TransposeToRef(this, result);
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the index-th row of the current matrix with the given 4 x float values
  5477. * @param index defines the row index
  5478. * @param x defines the x component to set
  5479. * @param y defines the y component to set
  5480. * @param z defines the z component to set
  5481. * @param w defines the w component to set
  5482. * @returns the updated current matrix
  5483. */
  5484. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5485. if (index < 0 || index > 3) {
  5486. return this;
  5487. }
  5488. var i = index * 4;
  5489. this.m[i + 0] = x;
  5490. this.m[i + 1] = y;
  5491. this.m[i + 2] = z;
  5492. this.m[i + 3] = w;
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5498. * @param scale defines the scale factor
  5499. * @returns a new matrix
  5500. */
  5501. Matrix.prototype.scale = function (scale) {
  5502. var result = new Matrix();
  5503. this.scaleToRef(scale, result);
  5504. return result;
  5505. };
  5506. /**
  5507. * Scale the current matrix values by a factor to a given result matrix
  5508. * @param scale defines the scale factor
  5509. * @param result defines the matrix to store the result
  5510. * @returns the current matrix
  5511. */
  5512. Matrix.prototype.scaleToRef = function (scale, result) {
  5513. for (var index = 0; index < 16; index++) {
  5514. result.m[index] = this.m[index] * scale;
  5515. }
  5516. result._markAsUpdated();
  5517. return this;
  5518. };
  5519. /**
  5520. * Scale the current matrix values by a factor and add the result to a given matrix
  5521. * @param scale defines the scale factor
  5522. * @param result defines the Matrix to store the result
  5523. * @returns the current matrix
  5524. */
  5525. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5526. for (var index = 0; index < 16; index++) {
  5527. result.m[index] += this.m[index] * scale;
  5528. }
  5529. result._markAsUpdated();
  5530. return this;
  5531. };
  5532. /**
  5533. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5534. * @param ref matrix to store the result
  5535. */
  5536. Matrix.prototype.toNormalMatrix = function (ref) {
  5537. this.invertToRef(ref);
  5538. ref.transpose();
  5539. var m = ref.m;
  5540. 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);
  5541. };
  5542. /**
  5543. * Gets only rotation part of the current matrix
  5544. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5545. */
  5546. Matrix.prototype.getRotationMatrix = function () {
  5547. var result = Matrix.Identity();
  5548. this.getRotationMatrixToRef(result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5553. * @param result defines the target matrix to store data to
  5554. * @returns the current matrix
  5555. */
  5556. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5557. var m = this.m;
  5558. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5559. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5560. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5561. if (this.determinant() <= 0) {
  5562. sy *= -1;
  5563. }
  5564. if (sx === 0 || sy === 0 || sz === 0) {
  5565. Matrix.IdentityToRef(result);
  5566. }
  5567. else {
  5568. 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);
  5569. }
  5570. return this;
  5571. };
  5572. // Statics
  5573. /**
  5574. * Creates a matrix from an array
  5575. * @param array defines the source array
  5576. * @param offset defines an offset in the source array
  5577. * @returns a new Matrix set from the starting index of the given array
  5578. */
  5579. Matrix.FromArray = function (array, offset) {
  5580. var result = new Matrix();
  5581. if (!offset) {
  5582. offset = 0;
  5583. }
  5584. Matrix.FromArrayToRef(array, offset, result);
  5585. return result;
  5586. };
  5587. /**
  5588. * Copy the content of an array into a given matrix
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @param result defines the target matrix
  5592. */
  5593. Matrix.FromArrayToRef = function (array, offset, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] = array[index + offset];
  5596. }
  5597. result._markAsUpdated();
  5598. };
  5599. /**
  5600. * Stores an array into a matrix after having multiplied each component by a given factor
  5601. * @param array defines the source array
  5602. * @param offset defines the offset in the source array
  5603. * @param scale defines the scaling factor
  5604. * @param result defines the target matrix
  5605. */
  5606. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5607. for (var index = 0; index < 16; index++) {
  5608. result.m[index] = array[index + offset] * scale;
  5609. }
  5610. result._markAsUpdated();
  5611. };
  5612. /**
  5613. * Stores a list of values (16) inside a given matrix
  5614. * @param initialM11 defines 1st value of 1st row
  5615. * @param initialM12 defines 2nd value of 1st row
  5616. * @param initialM13 defines 3rd value of 1st row
  5617. * @param initialM14 defines 4th value of 1st row
  5618. * @param initialM21 defines 1st value of 2nd row
  5619. * @param initialM22 defines 2nd value of 2nd row
  5620. * @param initialM23 defines 3rd value of 2nd row
  5621. * @param initialM24 defines 4th value of 2nd row
  5622. * @param initialM31 defines 1st value of 3rd row
  5623. * @param initialM32 defines 2nd value of 3rd row
  5624. * @param initialM33 defines 3rd value of 3rd row
  5625. * @param initialM34 defines 4th value of 3rd row
  5626. * @param initialM41 defines 1st value of 4th row
  5627. * @param initialM42 defines 2nd value of 4th row
  5628. * @param initialM43 defines 3rd value of 4th row
  5629. * @param initialM44 defines 4th value of 4th row
  5630. * @param result defines the target matrix
  5631. */
  5632. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5633. result.m[0] = initialM11;
  5634. result.m[1] = initialM12;
  5635. result.m[2] = initialM13;
  5636. result.m[3] = initialM14;
  5637. result.m[4] = initialM21;
  5638. result.m[5] = initialM22;
  5639. result.m[6] = initialM23;
  5640. result.m[7] = initialM24;
  5641. result.m[8] = initialM31;
  5642. result.m[9] = initialM32;
  5643. result.m[10] = initialM33;
  5644. result.m[11] = initialM34;
  5645. result.m[12] = initialM41;
  5646. result.m[13] = initialM42;
  5647. result.m[14] = initialM43;
  5648. result.m[15] = initialM44;
  5649. result._markAsUpdated();
  5650. };
  5651. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5652. /**
  5653. * Gets an identity matrix that must not be updated
  5654. */
  5655. get: function () {
  5656. return Matrix._identityReadOnly;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. /**
  5662. * Creates new matrix from a list of values (16)
  5663. * @param initialM11 defines 1st value of 1st row
  5664. * @param initialM12 defines 2nd value of 1st row
  5665. * @param initialM13 defines 3rd value of 1st row
  5666. * @param initialM14 defines 4th value of 1st row
  5667. * @param initialM21 defines 1st value of 2nd row
  5668. * @param initialM22 defines 2nd value of 2nd row
  5669. * @param initialM23 defines 3rd value of 2nd row
  5670. * @param initialM24 defines 4th value of 2nd row
  5671. * @param initialM31 defines 1st value of 3rd row
  5672. * @param initialM32 defines 2nd value of 3rd row
  5673. * @param initialM33 defines 3rd value of 3rd row
  5674. * @param initialM34 defines 4th value of 3rd row
  5675. * @param initialM41 defines 1st value of 4th row
  5676. * @param initialM42 defines 2nd value of 4th row
  5677. * @param initialM43 defines 3rd value of 4th row
  5678. * @param initialM44 defines 4th value of 4th row
  5679. * @returns the new matrix
  5680. */
  5681. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5682. var result = new Matrix();
  5683. result.m[0] = initialM11;
  5684. result.m[1] = initialM12;
  5685. result.m[2] = initialM13;
  5686. result.m[3] = initialM14;
  5687. result.m[4] = initialM21;
  5688. result.m[5] = initialM22;
  5689. result.m[6] = initialM23;
  5690. result.m[7] = initialM24;
  5691. result.m[8] = initialM31;
  5692. result.m[9] = initialM32;
  5693. result.m[10] = initialM33;
  5694. result.m[11] = initialM34;
  5695. result.m[12] = initialM41;
  5696. result.m[13] = initialM42;
  5697. result.m[14] = initialM43;
  5698. result.m[15] = initialM44;
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @returns a new matrix
  5707. */
  5708. Matrix.Compose = function (scale, rotation, translation) {
  5709. var result = Matrix.Identity();
  5710. Matrix.ComposeToRef(scale, rotation, translation, result);
  5711. return result;
  5712. };
  5713. /**
  5714. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5715. * @param scale defines the scale vector3
  5716. * @param rotation defines the rotation quaternion
  5717. * @param translation defines the translation vector3
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5721. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5722. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5723. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5724. result.setTranslation(translation);
  5725. };
  5726. /**
  5727. * Creates a new identity matrix
  5728. * @returns a new identity matrix
  5729. */
  5730. Matrix.Identity = function () {
  5731. 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);
  5732. };
  5733. /**
  5734. * Creates a new identity matrix and stores the result in a given matrix
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.IdentityToRef = function (result) {
  5738. 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);
  5739. };
  5740. /**
  5741. * Creates a new zero matrix
  5742. * @returns a new zero matrix
  5743. */
  5744. Matrix.Zero = function () {
  5745. 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);
  5746. };
  5747. /**
  5748. * Creates a new rotation matrix for "angle" radians around the X axis
  5749. * @param angle defines the angle (in radians) to use
  5750. * @return the new matrix
  5751. */
  5752. Matrix.RotationX = function (angle) {
  5753. var result = new Matrix();
  5754. Matrix.RotationXToRef(angle, result);
  5755. return result;
  5756. };
  5757. /**
  5758. * Creates a new matrix as the invert of a given matrix
  5759. * @param source defines the source matrix
  5760. * @returns the new matrix
  5761. */
  5762. Matrix.Invert = function (source) {
  5763. var result = new Matrix();
  5764. source.invertToRef(result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5769. * @param angle defines the angle (in radians) to use
  5770. * @param result defines the target matrix
  5771. */
  5772. Matrix.RotationXToRef = function (angle, result) {
  5773. var s = Math.sin(angle);
  5774. var c = Math.cos(angle);
  5775. result.m[0] = 1.0;
  5776. result.m[15] = 1.0;
  5777. result.m[5] = c;
  5778. result.m[10] = c;
  5779. result.m[9] = -s;
  5780. result.m[6] = s;
  5781. result.m[1] = 0.0;
  5782. result.m[2] = 0.0;
  5783. result.m[3] = 0.0;
  5784. result.m[4] = 0.0;
  5785. result.m[7] = 0.0;
  5786. result.m[8] = 0.0;
  5787. result.m[11] = 0.0;
  5788. result.m[12] = 0.0;
  5789. result.m[13] = 0.0;
  5790. result.m[14] = 0.0;
  5791. result._markAsUpdated();
  5792. };
  5793. /**
  5794. * Creates a new rotation matrix for "angle" radians around the Y axis
  5795. * @param angle defines the angle (in radians) to use
  5796. * @return the new matrix
  5797. */
  5798. Matrix.RotationY = function (angle) {
  5799. var result = new Matrix();
  5800. Matrix.RotationYToRef(angle, result);
  5801. return result;
  5802. };
  5803. /**
  5804. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5805. * @param angle defines the angle (in radians) to use
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.RotationYToRef = function (angle, result) {
  5809. var s = Math.sin(angle);
  5810. var c = Math.cos(angle);
  5811. result.m[5] = 1.0;
  5812. result.m[15] = 1.0;
  5813. result.m[0] = c;
  5814. result.m[2] = -s;
  5815. result.m[8] = s;
  5816. result.m[10] = c;
  5817. result.m[1] = 0.0;
  5818. result.m[3] = 0.0;
  5819. result.m[4] = 0.0;
  5820. result.m[6] = 0.0;
  5821. result.m[7] = 0.0;
  5822. result.m[9] = 0.0;
  5823. result.m[11] = 0.0;
  5824. result.m[12] = 0.0;
  5825. result.m[13] = 0.0;
  5826. result.m[14] = 0.0;
  5827. result._markAsUpdated();
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the Z axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationZ = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationZToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationZToRef = function (angle, result) {
  5845. var s = Math.sin(angle);
  5846. var c = Math.cos(angle);
  5847. result.m[10] = 1.0;
  5848. result.m[15] = 1.0;
  5849. result.m[0] = c;
  5850. result.m[1] = s;
  5851. result.m[4] = -s;
  5852. result.m[5] = c;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[6] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[9] = 0.0;
  5859. result.m[11] = 0.0;
  5860. result.m[12] = 0.0;
  5861. result.m[13] = 0.0;
  5862. result.m[14] = 0.0;
  5863. result._markAsUpdated();
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @return the new matrix
  5870. */
  5871. Matrix.RotationAxis = function (axis, angle) {
  5872. var result = Matrix.Zero();
  5873. Matrix.RotationAxisToRef(axis, angle, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @param result defines the target matrix
  5881. */
  5882. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5883. var s = Math.sin(-angle);
  5884. var c = Math.cos(-angle);
  5885. var c1 = 1 - c;
  5886. axis.normalize();
  5887. result.m[0] = (axis.x * axis.x) * c1 + c;
  5888. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5889. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5890. result.m[3] = 0.0;
  5891. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5892. result.m[5] = (axis.y * axis.y) * c1 + c;
  5893. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5894. result.m[7] = 0.0;
  5895. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5896. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5897. result.m[10] = (axis.z * axis.z) * c1 + c;
  5898. result.m[11] = 0.0;
  5899. result.m[15] = 1.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a rotation matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @returns the new rotation matrix
  5908. */
  5909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5910. var result = new Matrix();
  5911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a rotation matrix and stores it in a given matrix
  5916. * @param yaw defines the yaw angle in radians (Y axis)
  5917. * @param pitch defines the pitch angle in radians (X axis)
  5918. * @param roll defines the roll angle in radians (X axis)
  5919. * @param result defines the target matrix
  5920. */
  5921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5923. this._tempQuaternion.toRotationMatrix(result);
  5924. };
  5925. /**
  5926. * Creates a scaling matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Scaling = function (x, y, z) {
  5933. var result = Matrix.Zero();
  5934. Matrix.ScalingToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a scaling matrix and stores it in a given matrix
  5939. * @param x defines the scale factor on X axis
  5940. * @param y defines the scale factor on Y axis
  5941. * @param z defines the scale factor on Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.ScalingToRef = function (x, y, z, result) {
  5945. result.m[0] = x;
  5946. result.m[1] = 0.0;
  5947. result.m[2] = 0.0;
  5948. result.m[3] = 0.0;
  5949. result.m[4] = 0.0;
  5950. result.m[5] = y;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[10] = z;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result.m[15] = 1.0;
  5961. result._markAsUpdated();
  5962. };
  5963. /**
  5964. * Creates a translation matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @returns the new matrix
  5969. */
  5970. Matrix.Translation = function (x, y, z) {
  5971. var result = Matrix.Identity();
  5972. Matrix.TranslationToRef(x, y, z, result);
  5973. return result;
  5974. };
  5975. /**
  5976. * Creates a translation matrix and stores it in a given matrix
  5977. * @param x defines the translation on X axis
  5978. * @param y defines the translation on Y axis
  5979. * @param z defines the translationon Z axis
  5980. * @param result defines the target matrix
  5981. */
  5982. Matrix.TranslationToRef = function (x, y, z, result) {
  5983. 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);
  5984. };
  5985. /**
  5986. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Lerp = function (startValue, endValue, gradient) {
  5993. var result = Matrix.Zero();
  5994. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5999. * @param startValue defines the start value
  6000. * @param endValue defines the end value
  6001. * @param gradient defines the gradient factor
  6002. * @param result defines the Matrix object where to store data
  6003. */
  6004. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6005. for (var index = 0; index < 16; index++) {
  6006. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6007. }
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Builds a new matrix whose values are computed by:
  6012. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6013. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6014. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6015. * @param startValue defines the first matrix
  6016. * @param endValue defines the second matrix
  6017. * @param gradient defines the gradient between the two matrices
  6018. * @returns the new matrix
  6019. */
  6020. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6021. var result = Matrix.Zero();
  6022. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6023. return result;
  6024. };
  6025. /**
  6026. * Update a matrix to values which are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6036. var startScale = MathTmp.Vector3[0];
  6037. var startRotation = MathTmp.Quaternion[0];
  6038. var startTranslation = MathTmp.Vector3[1];
  6039. startValue.decompose(startScale, startRotation, startTranslation);
  6040. var endScale = MathTmp.Vector3[2];
  6041. var endRotation = MathTmp.Quaternion[1];
  6042. var endTranslation = MathTmp.Vector3[3];
  6043. endValue.decompose(endScale, endRotation, endTranslation);
  6044. var resultScale = MathTmp.Vector3[4];
  6045. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6046. var resultRotation = MathTmp.Quaternion[2];
  6047. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6048. var resultTranslation = MathTmp.Vector3[5];
  6049. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6050. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6051. };
  6052. /**
  6053. * 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"
  6054. * This function works in left handed mode
  6055. * @param eye defines the final position of the entity
  6056. * @param target defines where the entity should look at
  6057. * @param up defines the up vector for the entity
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.LookAtLH = function (eye, target, up) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LookAtLHToRef(eye, target, up, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * 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".
  6067. * This function works in left handed mode
  6068. * @param eye defines the final position of the entity
  6069. * @param target defines where the entity should look at
  6070. * @param up defines the up vector for the entity
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6074. // Z axis
  6075. target.subtractToRef(eye, this._zAxis);
  6076. this._zAxis.normalize();
  6077. // X axis
  6078. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6079. if (this._xAxis.lengthSquared() === 0) {
  6080. this._xAxis.x = 1.0;
  6081. }
  6082. else {
  6083. this._xAxis.normalize();
  6084. }
  6085. // Y axis
  6086. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6087. this._yAxis.normalize();
  6088. // Eye angles
  6089. var ex = -Vector3.Dot(this._xAxis, eye);
  6090. var ey = -Vector3.Dot(this._yAxis, eye);
  6091. var ez = -Vector3.Dot(this._zAxis, eye);
  6092. 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);
  6093. };
  6094. /**
  6095. * 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"
  6096. * This function works in right handed mode
  6097. * @param eye defines the final position of the entity
  6098. * @param target defines where the entity should look at
  6099. * @param up defines the up vector for the entity
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.LookAtRH = function (eye, target, up) {
  6103. var result = Matrix.Zero();
  6104. Matrix.LookAtRHToRef(eye, target, up, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * 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".
  6109. * This function works in right handed mode
  6110. * @param eye defines the final position of the entity
  6111. * @param target defines where the entity should look at
  6112. * @param up defines the up vector for the entity
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6116. // Z axis
  6117. eye.subtractToRef(target, this._zAxis);
  6118. this._zAxis.normalize();
  6119. // X axis
  6120. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6121. if (this._xAxis.lengthSquared() === 0) {
  6122. this._xAxis.x = 1.0;
  6123. }
  6124. else {
  6125. this._xAxis.normalize();
  6126. }
  6127. // Y axis
  6128. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6129. this._yAxis.normalize();
  6130. // Eye angles
  6131. var ex = -Vector3.Dot(this._xAxis, eye);
  6132. var ey = -Vector3.Dot(this._yAxis, eye);
  6133. var ez = -Vector3.Dot(this._zAxis, eye);
  6134. 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);
  6135. };
  6136. /**
  6137. * Create a left-handed orthographic projection matrix
  6138. * @param width defines the viewport width
  6139. * @param height defines the viewport height
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a left-handed orthographic projection matrix
  6143. */
  6144. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Store a left-handed orthographic projection to a given matrix
  6151. * @param width defines the viewport width
  6152. * @param height defines the viewport height
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6158. var n = znear;
  6159. var f = zfar;
  6160. var a = 2.0 / width;
  6161. var b = 2.0 / height;
  6162. var c = 2.0 / (f - n);
  6163. var d = -(f + n) / (f - n);
  6164. 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);
  6165. };
  6166. /**
  6167. * Create a left-handed orthographic projection matrix
  6168. * @param left defines the viewport left coordinate
  6169. * @param right defines the viewport right coordinate
  6170. * @param bottom defines the viewport bottom coordinate
  6171. * @param top defines the viewport top coordinate
  6172. * @param znear defines the near clip plane
  6173. * @param zfar defines the far clip plane
  6174. * @returns a new matrix as a left-handed orthographic projection matrix
  6175. */
  6176. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6177. var matrix = Matrix.Zero();
  6178. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6179. return matrix;
  6180. };
  6181. /**
  6182. * Stores a left-handed orthographic projection into a given matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @param result defines the target matrix
  6190. */
  6191. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6192. var n = znear;
  6193. var f = zfar;
  6194. var a = 2.0 / (right - left);
  6195. var b = 2.0 / (top - bottom);
  6196. var c = 2.0 / (f - n);
  6197. var d = -(f + n) / (f - n);
  6198. var i0 = (left + right) / (left - right);
  6199. var i1 = (top + bottom) / (bottom - top);
  6200. 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);
  6201. };
  6202. /**
  6203. * Creates a right-handed orthographic projection matrix
  6204. * @param left defines the viewport left coordinate
  6205. * @param right defines the viewport right coordinate
  6206. * @param bottom defines the viewport bottom coordinate
  6207. * @param top defines the viewport top coordinate
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a right-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Stores a right-handed orthographic projection into a given matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @param result defines the target matrix
  6226. */
  6227. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6228. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6229. result.m[10] *= -1.0;
  6230. };
  6231. /**
  6232. * Creates a left-handed perspective projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed perspective projection matrix
  6238. */
  6239. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 * n / width;
  6244. var b = 2.0 * n / height;
  6245. var c = (f + n) / (f - n);
  6246. var d = -2.0 * f * n / (f - n);
  6247. 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);
  6248. return matrix;
  6249. };
  6250. /**
  6251. * Creates a left-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6274. var n = znear;
  6275. var f = zfar;
  6276. var t = 1.0 / (Math.tan(fov * 0.5));
  6277. var a = isVerticalFovFixed ? (t / aspect) : t;
  6278. var b = isVerticalFovFixed ? t : (t * aspect);
  6279. var c = (f + n) / (f - n);
  6280. var d = -2.0 * f * n / (f - n);
  6281. 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);
  6282. };
  6283. /**
  6284. * Creates a right-handed perspective projection matrix
  6285. * @param fov defines the horizontal field of view
  6286. * @param aspect defines the aspect ratio
  6287. * @param znear defines the near clip plane
  6288. * @param zfar defines the far clip plane
  6289. * @returns a new matrix as a right-handed perspective projection matrix
  6290. */
  6291. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6292. var matrix = Matrix.Zero();
  6293. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6294. return matrix;
  6295. };
  6296. /**
  6297. * Stores a right-handed perspective projection into a given matrix
  6298. * @param fov defines the horizontal field of view
  6299. * @param aspect defines the aspect ratio
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @param result defines the target matrix
  6303. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6304. */
  6305. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6306. //alternatively this could be expressed as:
  6307. // m = PerspectiveFovLHToRef
  6308. // m[10] *= -1.0;
  6309. // m[11] *= -1.0;
  6310. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6311. var n = znear;
  6312. var f = zfar;
  6313. var t = 1.0 / (Math.tan(fov * 0.5));
  6314. var a = isVerticalFovFixed ? (t / aspect) : t;
  6315. var b = isVerticalFovFixed ? t : (t * aspect);
  6316. var c = -(f + n) / (f - n);
  6317. var d = -2 * f * n / (f - n);
  6318. 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);
  6319. };
  6320. /**
  6321. * Stores a perspective projection for WebVR info a given matrix
  6322. * @param fov defines the field of view
  6323. * @param znear defines the near clip plane
  6324. * @param zfar defines the far clip plane
  6325. * @param result defines the target matrix
  6326. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6327. */
  6328. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6329. if (rightHanded === void 0) { rightHanded = false; }
  6330. var rightHandedFactor = rightHanded ? -1 : 1;
  6331. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6332. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6333. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6334. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6335. var xScale = 2.0 / (leftTan + rightTan);
  6336. var yScale = 2.0 / (upTan + downTan);
  6337. result.m[0] = xScale;
  6338. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6339. result.m[5] = yScale;
  6340. result.m[6] = result.m[7] = 0.0;
  6341. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6342. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6343. result.m[10] = -zfar / (znear - zfar);
  6344. result.m[11] = 1.0 * rightHandedFactor;
  6345. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6346. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6347. result._markAsUpdated();
  6348. };
  6349. /**
  6350. * Computes a complete transformation matrix
  6351. * @param viewport defines the viewport to use
  6352. * @param world defines the world matrix
  6353. * @param view defines the view matrix
  6354. * @param projection defines the projection matrix
  6355. * @param zmin defines the near clip plane
  6356. * @param zmax defines the far clip plane
  6357. * @returns the transformation matrix
  6358. */
  6359. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6360. var cw = viewport.width;
  6361. var ch = viewport.height;
  6362. var cx = viewport.x;
  6363. var cy = viewport.y;
  6364. 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);
  6365. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6366. };
  6367. /**
  6368. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix2x2 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1],
  6375. matrix.m[4], matrix.m[5]
  6376. ]);
  6377. };
  6378. /**
  6379. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix3x3 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1], matrix.m[2],
  6386. matrix.m[4], matrix.m[5], matrix.m[6],
  6387. matrix.m[8], matrix.m[9], matrix.m[10]
  6388. ]);
  6389. };
  6390. /**
  6391. * Compute the transpose of a given matrix
  6392. * @param matrix defines the matrix to transpose
  6393. * @returns the new matrix
  6394. */
  6395. Matrix.Transpose = function (matrix) {
  6396. var result = new Matrix();
  6397. Matrix.TransposeToRef(matrix, result);
  6398. return result;
  6399. };
  6400. /**
  6401. * Compute the transpose of a matrix and store it in a target matrix
  6402. * @param matrix defines the matrix to transpose
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.TransposeToRef = function (matrix, result) {
  6406. result.m[0] = matrix.m[0];
  6407. result.m[1] = matrix.m[4];
  6408. result.m[2] = matrix.m[8];
  6409. result.m[3] = matrix.m[12];
  6410. result.m[4] = matrix.m[1];
  6411. result.m[5] = matrix.m[5];
  6412. result.m[6] = matrix.m[9];
  6413. result.m[7] = matrix.m[13];
  6414. result.m[8] = matrix.m[2];
  6415. result.m[9] = matrix.m[6];
  6416. result.m[10] = matrix.m[10];
  6417. result.m[11] = matrix.m[14];
  6418. result.m[12] = matrix.m[3];
  6419. result.m[13] = matrix.m[7];
  6420. result.m[14] = matrix.m[11];
  6421. result.m[15] = matrix.m[15];
  6422. };
  6423. /**
  6424. * Computes a reflection matrix from a plane
  6425. * @param plane defines the reflection plane
  6426. * @returns a new matrix
  6427. */
  6428. Matrix.Reflection = function (plane) {
  6429. var matrix = new Matrix();
  6430. Matrix.ReflectionToRef(plane, matrix);
  6431. return matrix;
  6432. };
  6433. /**
  6434. * Computes a reflection matrix from a plane
  6435. * @param plane defines the reflection plane
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.ReflectionToRef = function (plane, result) {
  6439. plane.normalize();
  6440. var x = plane.normal.x;
  6441. var y = plane.normal.y;
  6442. var z = plane.normal.z;
  6443. var temp = -2 * x;
  6444. var temp2 = -2 * y;
  6445. var temp3 = -2 * z;
  6446. result.m[0] = (temp * x) + 1;
  6447. result.m[1] = temp2 * x;
  6448. result.m[2] = temp3 * x;
  6449. result.m[3] = 0.0;
  6450. result.m[4] = temp * y;
  6451. result.m[5] = (temp2 * y) + 1;
  6452. result.m[6] = temp3 * y;
  6453. result.m[7] = 0.0;
  6454. result.m[8] = temp * z;
  6455. result.m[9] = temp2 * z;
  6456. result.m[10] = (temp3 * z) + 1;
  6457. result.m[11] = 0.0;
  6458. result.m[12] = temp * plane.d;
  6459. result.m[13] = temp2 * plane.d;
  6460. result.m[14] = temp3 * plane.d;
  6461. result.m[15] = 1.0;
  6462. result._markAsUpdated();
  6463. };
  6464. /**
  6465. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6466. * @param xaxis defines the value of the 1st axis
  6467. * @param yaxis defines the value of the 2nd axis
  6468. * @param zaxis defines the value of the 3rd axis
  6469. * @param result defines the target matrix
  6470. */
  6471. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6472. result.m[0] = xaxis.x;
  6473. result.m[1] = xaxis.y;
  6474. result.m[2] = xaxis.z;
  6475. result.m[3] = 0.0;
  6476. result.m[4] = yaxis.x;
  6477. result.m[5] = yaxis.y;
  6478. result.m[6] = yaxis.z;
  6479. result.m[7] = 0.0;
  6480. result.m[8] = zaxis.x;
  6481. result.m[9] = zaxis.y;
  6482. result.m[10] = zaxis.z;
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. /**
  6491. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6492. * @param quat defines the quaternion to use
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.FromQuaternionToRef = function (quat, result) {
  6496. var xx = quat.x * quat.x;
  6497. var yy = quat.y * quat.y;
  6498. var zz = quat.z * quat.z;
  6499. var xy = quat.x * quat.y;
  6500. var zw = quat.z * quat.w;
  6501. var zx = quat.z * quat.x;
  6502. var yw = quat.y * quat.w;
  6503. var yz = quat.y * quat.z;
  6504. var xw = quat.x * quat.w;
  6505. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6506. result.m[1] = 2.0 * (xy + zw);
  6507. result.m[2] = 2.0 * (zx - yw);
  6508. result.m[3] = 0.0;
  6509. result.m[4] = 2.0 * (xy - zw);
  6510. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6511. result.m[6] = 2.0 * (yz + xw);
  6512. result.m[7] = 0.0;
  6513. result.m[8] = 2.0 * (zx + yw);
  6514. result.m[9] = 2.0 * (yz - xw);
  6515. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6516. result.m[11] = 0.0;
  6517. result.m[12] = 0.0;
  6518. result.m[13] = 0.0;
  6519. result.m[14] = 0.0;
  6520. result.m[15] = 1.0;
  6521. result._markAsUpdated();
  6522. };
  6523. Matrix._tempQuaternion = new Quaternion();
  6524. Matrix._xAxis = Vector3.Zero();
  6525. Matrix._yAxis = Vector3.Zero();
  6526. Matrix._zAxis = Vector3.Zero();
  6527. Matrix._updateFlagSeed = 0;
  6528. Matrix._identityReadOnly = Matrix.Identity();
  6529. return Matrix;
  6530. }());
  6531. BABYLON.Matrix = Matrix;
  6532. var Plane = /** @class */ (function () {
  6533. /**
  6534. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6535. */
  6536. function Plane(a, b, c, d) {
  6537. this.normal = new Vector3(a, b, c);
  6538. this.d = d;
  6539. }
  6540. /**
  6541. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6542. */
  6543. Plane.prototype.asArray = function () {
  6544. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6545. };
  6546. // Methods
  6547. /**
  6548. * Returns a new plane copied from the current Plane.
  6549. */
  6550. Plane.prototype.clone = function () {
  6551. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6552. };
  6553. /**
  6554. * Returns the string "Plane".
  6555. */
  6556. Plane.prototype.getClassName = function () {
  6557. return "Plane";
  6558. };
  6559. /**
  6560. * Returns the Plane hash code.
  6561. */
  6562. Plane.prototype.getHashCode = function () {
  6563. var hash = this.normal.getHashCode();
  6564. hash = (hash * 397) ^ (this.d || 0);
  6565. return hash;
  6566. };
  6567. /**
  6568. * Normalize the current Plane in place.
  6569. * Returns the updated Plane.
  6570. */
  6571. Plane.prototype.normalize = function () {
  6572. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6573. var magnitude = 0.0;
  6574. if (norm !== 0) {
  6575. magnitude = 1.0 / norm;
  6576. }
  6577. this.normal.x *= magnitude;
  6578. this.normal.y *= magnitude;
  6579. this.normal.z *= magnitude;
  6580. this.d *= magnitude;
  6581. return this;
  6582. };
  6583. /**
  6584. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6585. */
  6586. Plane.prototype.transform = function (transformation) {
  6587. var transposedMatrix = Matrix.Transpose(transformation);
  6588. var x = this.normal.x;
  6589. var y = this.normal.y;
  6590. var z = this.normal.z;
  6591. var d = this.d;
  6592. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6593. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6594. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6595. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6596. return new Plane(normalX, normalY, normalZ, finalD);
  6597. };
  6598. /**
  6599. * Returns the dot product (float) of the point coordinates and the plane normal.
  6600. */
  6601. Plane.prototype.dotCoordinate = function (point) {
  6602. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6603. };
  6604. /**
  6605. * Updates the current Plane from the plane defined by the three given points.
  6606. * Returns the updated Plane.
  6607. */
  6608. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6609. var x1 = point2.x - point1.x;
  6610. var y1 = point2.y - point1.y;
  6611. var z1 = point2.z - point1.z;
  6612. var x2 = point3.x - point1.x;
  6613. var y2 = point3.y - point1.y;
  6614. var z2 = point3.z - point1.z;
  6615. var yz = (y1 * z2) - (z1 * y2);
  6616. var xz = (z1 * x2) - (x1 * z2);
  6617. var xy = (x1 * y2) - (y1 * x2);
  6618. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6619. var invPyth;
  6620. if (pyth !== 0) {
  6621. invPyth = 1.0 / pyth;
  6622. }
  6623. else {
  6624. invPyth = 0.0;
  6625. }
  6626. this.normal.x = yz * invPyth;
  6627. this.normal.y = xz * invPyth;
  6628. this.normal.z = xy * invPyth;
  6629. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6630. return this;
  6631. };
  6632. /**
  6633. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6634. */
  6635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6636. var dot = Vector3.Dot(this.normal, direction);
  6637. return (dot <= epsilon);
  6638. };
  6639. /**
  6640. * Returns the signed distance (float) from the given point to the Plane.
  6641. */
  6642. Plane.prototype.signedDistanceTo = function (point) {
  6643. return Vector3.Dot(point, this.normal) + this.d;
  6644. };
  6645. // Statics
  6646. /**
  6647. * Returns a new Plane from the given array.
  6648. */
  6649. Plane.FromArray = function (array) {
  6650. return new Plane(array[0], array[1], array[2], array[3]);
  6651. };
  6652. /**
  6653. * Returns a new Plane defined by the three given points.
  6654. */
  6655. Plane.FromPoints = function (point1, point2, point3) {
  6656. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6657. result.copyFromPoints(point1, point2, point3);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns a new Plane the normal vector to this plane at the given origin point.
  6662. * Note : the vector "normal" is updated because normalized.
  6663. */
  6664. Plane.FromPositionAndNormal = function (origin, normal) {
  6665. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6666. normal.normalize();
  6667. result.normal = normal;
  6668. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6673. */
  6674. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6675. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6676. return Vector3.Dot(point, normal) + d;
  6677. };
  6678. return Plane;
  6679. }());
  6680. BABYLON.Plane = Plane;
  6681. var Viewport = /** @class */ (function () {
  6682. /**
  6683. * Creates a Viewport object located at (x, y) and sized (width, height).
  6684. */
  6685. function Viewport(x, y, width, height) {
  6686. this.x = x;
  6687. this.y = y;
  6688. this.width = width;
  6689. this.height = height;
  6690. }
  6691. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6692. if (renderWidthOrEngine.getRenderWidth) {
  6693. var engine = renderWidthOrEngine;
  6694. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6695. }
  6696. var renderWidth = renderWidthOrEngine;
  6697. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6698. };
  6699. /**
  6700. * Returns a new Viewport copied from the current one.
  6701. */
  6702. Viewport.prototype.clone = function () {
  6703. return new Viewport(this.x, this.y, this.width, this.height);
  6704. };
  6705. return Viewport;
  6706. }());
  6707. BABYLON.Viewport = Viewport;
  6708. var Frustum = /** @class */ (function () {
  6709. function Frustum() {
  6710. }
  6711. /**
  6712. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6713. */
  6714. Frustum.GetPlanes = function (transform) {
  6715. var frustumPlanes = [];
  6716. for (var index = 0; index < 6; index++) {
  6717. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6718. }
  6719. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6720. return frustumPlanes;
  6721. };
  6722. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6723. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6724. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6725. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6726. frustumPlane.d = transform.m[15] + transform.m[14];
  6727. frustumPlane.normalize();
  6728. };
  6729. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6730. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6731. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6732. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6733. frustumPlane.d = transform.m[15] - transform.m[14];
  6734. frustumPlane.normalize();
  6735. };
  6736. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6740. frustumPlane.d = transform.m[15] + transform.m[12];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6747. frustumPlane.d = transform.m[15] - transform.m[12];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6752. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6753. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6754. frustumPlane.d = transform.m[15] - transform.m[13];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6759. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6760. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6761. frustumPlane.d = transform.m[15] + transform.m[13];
  6762. frustumPlane.normalize();
  6763. };
  6764. /**
  6765. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6766. */
  6767. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6768. // Near
  6769. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6770. // Far
  6771. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6772. // Left
  6773. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6774. // Right
  6775. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6776. // Top
  6777. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6778. // Bottom
  6779. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6780. };
  6781. return Frustum;
  6782. }());
  6783. BABYLON.Frustum = Frustum;
  6784. /** Defines supported spaces */
  6785. var Space;
  6786. (function (Space) {
  6787. /** Local (object) space */
  6788. Space[Space["LOCAL"] = 0] = "LOCAL";
  6789. /** World space */
  6790. Space[Space["WORLD"] = 1] = "WORLD";
  6791. /** Bone space */
  6792. Space[Space["BONE"] = 2] = "BONE";
  6793. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6794. /** Defines the 3 main axes */
  6795. var Axis = /** @class */ (function () {
  6796. function Axis() {
  6797. }
  6798. /** X axis */
  6799. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6800. /** Y axis */
  6801. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6802. /** Z axis */
  6803. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6804. return Axis;
  6805. }());
  6806. BABYLON.Axis = Axis;
  6807. ;
  6808. var BezierCurve = /** @class */ (function () {
  6809. function BezierCurve() {
  6810. }
  6811. /**
  6812. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6813. */
  6814. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6815. // Extract X (which is equal to time here)
  6816. var f0 = 1 - 3 * x2 + 3 * x1;
  6817. var f1 = 3 * x2 - 6 * x1;
  6818. var f2 = 3 * x1;
  6819. var refinedT = t;
  6820. for (var i = 0; i < 5; i++) {
  6821. var refinedT2 = refinedT * refinedT;
  6822. var refinedT3 = refinedT2 * refinedT;
  6823. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6824. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6825. refinedT -= (x - t) * slope;
  6826. refinedT = Math.min(1, Math.max(0, refinedT));
  6827. }
  6828. // Resolve cubic bezier for the given x
  6829. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6830. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6831. Math.pow(refinedT, 3);
  6832. };
  6833. return BezierCurve;
  6834. }());
  6835. BABYLON.BezierCurve = BezierCurve;
  6836. /**
  6837. * Defines potential orientation for back face culling
  6838. */
  6839. var Orientation;
  6840. (function (Orientation) {
  6841. /**
  6842. * Clockwise
  6843. */
  6844. Orientation[Orientation["CW"] = 0] = "CW";
  6845. /** Counter clockwise */
  6846. Orientation[Orientation["CCW"] = 1] = "CCW";
  6847. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6848. /**
  6849. * Defines angle representation
  6850. */
  6851. var Angle = /** @class */ (function () {
  6852. /**
  6853. * Creates an Angle object of "radians" radians (float).
  6854. */
  6855. function Angle(radians) {
  6856. this._radians = radians;
  6857. if (this._radians < 0.0)
  6858. this._radians += (2.0 * Math.PI);
  6859. }
  6860. /**
  6861. * Get value in degrees
  6862. * @returns the Angle value in degrees (float)
  6863. */
  6864. Angle.prototype.degrees = function () {
  6865. return this._radians * 180.0 / Math.PI;
  6866. };
  6867. /**
  6868. * Get value in radians
  6869. * @returns the Angle value in radians (float)
  6870. */
  6871. Angle.prototype.radians = function () {
  6872. return this._radians;
  6873. };
  6874. /**
  6875. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6876. * @param a defines first vector
  6877. * @param b defines second vector
  6878. * @returns a new Angle
  6879. */
  6880. Angle.BetweenTwoPoints = function (a, b) {
  6881. var delta = b.subtract(a);
  6882. var theta = Math.atan2(delta.y, delta.x);
  6883. return new Angle(theta);
  6884. };
  6885. /**
  6886. * Gets a new Angle object from the given float in radians
  6887. * @param radians defines the angle value in radians
  6888. * @returns a new Angle
  6889. */
  6890. Angle.FromRadians = function (radians) {
  6891. return new Angle(radians);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in degrees
  6895. * @param degrees defines the angle value in degrees
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromDegrees = function (degrees) {
  6899. return new Angle(degrees * Math.PI / 180.0);
  6900. };
  6901. return Angle;
  6902. }());
  6903. BABYLON.Angle = Angle;
  6904. var Arc2 = /** @class */ (function () {
  6905. /**
  6906. * Creates an Arc object from the three given points : start, middle and end.
  6907. */
  6908. function Arc2(startPoint, midPoint, endPoint) {
  6909. this.startPoint = startPoint;
  6910. this.midPoint = midPoint;
  6911. this.endPoint = endPoint;
  6912. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6913. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6914. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6915. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6916. 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);
  6917. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6918. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6919. var a1 = this.startAngle.degrees();
  6920. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6921. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6922. // angles correction
  6923. if (a2 - a1 > +180.0)
  6924. a2 -= 360.0;
  6925. if (a2 - a1 < -180.0)
  6926. a2 += 360.0;
  6927. if (a3 - a2 > +180.0)
  6928. a3 -= 360.0;
  6929. if (a3 - a2 < -180.0)
  6930. a3 += 360.0;
  6931. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6932. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6933. }
  6934. return Arc2;
  6935. }());
  6936. BABYLON.Arc2 = Arc2;
  6937. var Path2 = /** @class */ (function () {
  6938. /**
  6939. * Creates a Path2 object from the starting 2D coordinates x and y.
  6940. */
  6941. function Path2(x, y) {
  6942. this._points = new Array();
  6943. this._length = 0.0;
  6944. this.closed = false;
  6945. this._points.push(new Vector2(x, y));
  6946. }
  6947. /**
  6948. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6949. * Returns the updated Path2.
  6950. */
  6951. Path2.prototype.addLineTo = function (x, y) {
  6952. if (this.closed) {
  6953. return this;
  6954. }
  6955. var newPoint = new Vector2(x, y);
  6956. var previousPoint = this._points[this._points.length - 1];
  6957. this._points.push(newPoint);
  6958. this._length += newPoint.subtract(previousPoint).length();
  6959. return this;
  6960. };
  6961. /**
  6962. * 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.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6966. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var startPoint = this._points[this._points.length - 1];
  6971. var midPoint = new Vector2(midX, midY);
  6972. var endPoint = new Vector2(endX, endY);
  6973. var arc = new Arc2(startPoint, midPoint, endPoint);
  6974. var increment = arc.angle.radians() / numberOfSegments;
  6975. if (arc.orientation === Orientation.CW)
  6976. increment *= -1;
  6977. var currentAngle = arc.startAngle.radians() + increment;
  6978. for (var i = 0; i < numberOfSegments; i++) {
  6979. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6980. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6981. this.addLineTo(x, y);
  6982. currentAngle += increment;
  6983. }
  6984. return this;
  6985. };
  6986. /**
  6987. * Closes the Path2.
  6988. * Returns the Path2.
  6989. */
  6990. Path2.prototype.close = function () {
  6991. this.closed = true;
  6992. return this;
  6993. };
  6994. /**
  6995. * Returns the Path2 total length (float).
  6996. */
  6997. Path2.prototype.length = function () {
  6998. var result = this._length;
  6999. if (!this.closed) {
  7000. var lastPoint = this._points[this._points.length - 1];
  7001. var firstPoint = this._points[0];
  7002. result += (firstPoint.subtract(lastPoint).length());
  7003. }
  7004. return result;
  7005. };
  7006. /**
  7007. * Returns the Path2 internal array of points.
  7008. */
  7009. Path2.prototype.getPoints = function () {
  7010. return this._points;
  7011. };
  7012. /**
  7013. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7014. */
  7015. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7016. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7017. return Vector2.Zero();
  7018. }
  7019. var lengthPosition = normalizedLengthPosition * this.length();
  7020. var previousOffset = 0;
  7021. for (var i = 0; i < this._points.length; i++) {
  7022. var j = (i + 1) % this._points.length;
  7023. var a = this._points[i];
  7024. var b = this._points[j];
  7025. var bToA = b.subtract(a);
  7026. var nextOffset = (bToA.length() + previousOffset);
  7027. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7028. var dir = bToA.normalize();
  7029. var localOffset = lengthPosition - previousOffset;
  7030. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7031. }
  7032. previousOffset = nextOffset;
  7033. }
  7034. return Vector2.Zero();
  7035. };
  7036. /**
  7037. * Returns a new Path2 starting at the coordinates (x, y).
  7038. */
  7039. Path2.StartingAt = function (x, y) {
  7040. return new Path2(x, y);
  7041. };
  7042. return Path2;
  7043. }());
  7044. BABYLON.Path2 = Path2;
  7045. var Path3D = /** @class */ (function () {
  7046. /**
  7047. * new Path3D(path, normal, raw)
  7048. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7049. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7050. * path : an array of Vector3, the curve axis of the Path3D
  7051. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7052. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7053. */
  7054. function Path3D(path, firstNormal, raw) {
  7055. if (firstNormal === void 0) { firstNormal = null; }
  7056. this.path = path;
  7057. this._curve = new Array();
  7058. this._distances = new Array();
  7059. this._tangents = new Array();
  7060. this._normals = new Array();
  7061. this._binormals = new Array();
  7062. for (var p = 0; p < path.length; p++) {
  7063. this._curve[p] = path[p].clone(); // hard copy
  7064. }
  7065. this._raw = raw || false;
  7066. this._compute(firstNormal);
  7067. }
  7068. /**
  7069. * Returns the Path3D array of successive Vector3 designing its curve.
  7070. */
  7071. Path3D.prototype.getCurve = function () {
  7072. return this._curve;
  7073. };
  7074. /**
  7075. * Returns an array populated with tangent vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getTangents = function () {
  7078. return this._tangents;
  7079. };
  7080. /**
  7081. * Returns an array populated with normal vectors on each Path3D curve point.
  7082. */
  7083. Path3D.prototype.getNormals = function () {
  7084. return this._normals;
  7085. };
  7086. /**
  7087. * Returns an array populated with binormal vectors on each Path3D curve point.
  7088. */
  7089. Path3D.prototype.getBinormals = function () {
  7090. return this._binormals;
  7091. };
  7092. /**
  7093. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7094. */
  7095. Path3D.prototype.getDistances = function () {
  7096. return this._distances;
  7097. };
  7098. /**
  7099. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7100. * Returns the same object updated.
  7101. */
  7102. Path3D.prototype.update = function (path, firstNormal) {
  7103. if (firstNormal === void 0) { firstNormal = null; }
  7104. for (var p = 0; p < path.length; p++) {
  7105. this._curve[p].x = path[p].x;
  7106. this._curve[p].y = path[p].y;
  7107. this._curve[p].z = path[p].z;
  7108. }
  7109. this._compute(firstNormal);
  7110. return this;
  7111. };
  7112. // private function compute() : computes tangents, normals and binormals
  7113. Path3D.prototype._compute = function (firstNormal) {
  7114. var l = this._curve.length;
  7115. // first and last tangents
  7116. this._tangents[0] = this._getFirstNonNullVector(0);
  7117. if (!this._raw) {
  7118. this._tangents[0].normalize();
  7119. }
  7120. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7121. if (!this._raw) {
  7122. this._tangents[l - 1].normalize();
  7123. }
  7124. // normals and binormals at first point : arbitrary vector with _normalVector()
  7125. var tg0 = this._tangents[0];
  7126. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7127. this._normals[0] = pp0;
  7128. if (!this._raw) {
  7129. this._normals[0].normalize();
  7130. }
  7131. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7132. if (!this._raw) {
  7133. this._binormals[0].normalize();
  7134. }
  7135. this._distances[0] = 0.0;
  7136. // normals and binormals : next points
  7137. var prev; // previous vector (segment)
  7138. var cur; // current vector (segment)
  7139. var curTang; // current tangent
  7140. // previous normal
  7141. var prevBinor; // previous binormal
  7142. for (var i = 1; i < l; i++) {
  7143. // tangents
  7144. prev = this._getLastNonNullVector(i);
  7145. if (i < l - 1) {
  7146. cur = this._getFirstNonNullVector(i);
  7147. this._tangents[i] = prev.add(cur);
  7148. this._tangents[i].normalize();
  7149. }
  7150. this._distances[i] = this._distances[i - 1] + prev.length();
  7151. // normals and binormals
  7152. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7153. curTang = this._tangents[i];
  7154. prevBinor = this._binormals[i - 1];
  7155. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7156. if (!this._raw) {
  7157. this._normals[i].normalize();
  7158. }
  7159. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7160. if (!this._raw) {
  7161. this._binormals[i].normalize();
  7162. }
  7163. }
  7164. };
  7165. // private function getFirstNonNullVector(index)
  7166. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7167. Path3D.prototype._getFirstNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7170. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7171. i++;
  7172. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7173. }
  7174. return nNVector;
  7175. };
  7176. // private function getLastNonNullVector(index)
  7177. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7178. Path3D.prototype._getLastNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7181. while (nLVector.length() === 0 && index > i + 1) {
  7182. i++;
  7183. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7184. }
  7185. return nLVector;
  7186. };
  7187. // private function normalVector(v0, vt, va) :
  7188. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7189. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7190. Path3D.prototype._normalVector = function (v0, vt, va) {
  7191. var normal0;
  7192. var tgl = vt.length();
  7193. if (tgl === 0.0) {
  7194. tgl = 1.0;
  7195. }
  7196. if (va === undefined || va === null) {
  7197. var point;
  7198. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7199. point = new Vector3(0.0, -1.0, 0.0);
  7200. }
  7201. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7202. point = new Vector3(1.0, 0.0, 0.0);
  7203. }
  7204. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7205. point = new Vector3(0.0, 0.0, 1.0);
  7206. }
  7207. else {
  7208. point = Vector3.Zero();
  7209. }
  7210. normal0 = Vector3.Cross(vt, point);
  7211. }
  7212. else {
  7213. normal0 = Vector3.Cross(vt, va);
  7214. Vector3.CrossToRef(normal0, vt, normal0);
  7215. }
  7216. normal0.normalize();
  7217. return normal0;
  7218. };
  7219. return Path3D;
  7220. }());
  7221. BABYLON.Path3D = Path3D;
  7222. var Curve3 = /** @class */ (function () {
  7223. /**
  7224. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7225. * A Curve3 is designed from a series of successive Vector3.
  7226. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7227. */
  7228. function Curve3(points) {
  7229. this._length = 0.0;
  7230. this._points = points;
  7231. this._length = this._computeLength(points);
  7232. }
  7233. /**
  7234. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7235. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7236. * @param v1 (Vector3) the control point
  7237. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7238. * @param nbPoints (integer) the wanted number of points in the curve
  7239. */
  7240. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7241. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7242. var bez = new Array();
  7243. var equation = function (t, val0, val1, val2) {
  7244. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7245. return res;
  7246. };
  7247. for (var i = 0; i <= nbPoints; i++) {
  7248. 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)));
  7249. }
  7250. return new Curve3(bez);
  7251. };
  7252. /**
  7253. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7254. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7255. * @param v1 (Vector3) the first control point
  7256. * @param v2 (Vector3) the second control point
  7257. * @param v3 (Vector3) the end point of the Cubic Bezier
  7258. * @param nbPoints (integer) the wanted number of points in the curve
  7259. */
  7260. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7261. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7262. var bez = new Array();
  7263. var equation = function (t, val0, val1, val2, val3) {
  7264. 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;
  7265. return res;
  7266. };
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. 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)));
  7269. }
  7270. return new Curve3(bez);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7274. * @param p1 (Vector3) the origin point of the Hermite Spline
  7275. * @param t1 (Vector3) the tangent vector at the origin point
  7276. * @param p2 (Vector3) the end point of the Hermite Spline
  7277. * @param t2 (Vector3) the tangent vector at the end point
  7278. * @param nbPoints (integer) the wanted number of points in the curve
  7279. */
  7280. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7281. var hermite = new Array();
  7282. var step = 1.0 / nbPoints;
  7283. for (var i = 0; i <= nbPoints; i++) {
  7284. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7285. }
  7286. return new Curve3(hermite);
  7287. };
  7288. /**
  7289. * Returns a Curve3 object along a CatmullRom Spline curve :
  7290. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7291. * @param nbPoints (integer) the wanted number of points between each curve control points
  7292. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7293. */
  7294. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7295. var catmullRom = new Array();
  7296. var step = 1.0 / nbPoints;
  7297. var amount = 0.0;
  7298. if (closed) {
  7299. var pointsCount = points.length;
  7300. for (var i = 0; i < pointsCount; i++) {
  7301. amount = 0;
  7302. for (var c = 0; c < nbPoints; c++) {
  7303. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7304. amount += step;
  7305. }
  7306. }
  7307. catmullRom.push(catmullRom[0]);
  7308. }
  7309. else {
  7310. var totalPoints = new Array();
  7311. totalPoints.push(points[0].clone());
  7312. Array.prototype.push.apply(totalPoints, points);
  7313. totalPoints.push(points[points.length - 1].clone());
  7314. for (var i = 0; i < totalPoints.length - 3; i++) {
  7315. amount = 0;
  7316. for (var c = 0; c < nbPoints; c++) {
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. amount += step;
  7319. }
  7320. }
  7321. i--;
  7322. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7323. }
  7324. return new Curve3(catmullRom);
  7325. };
  7326. /**
  7327. * Returns the Curve3 stored array of successive Vector3
  7328. */
  7329. Curve3.prototype.getPoints = function () {
  7330. return this._points;
  7331. };
  7332. /**
  7333. * Returns the computed length (float) of the curve.
  7334. */
  7335. Curve3.prototype.length = function () {
  7336. return this._length;
  7337. };
  7338. /**
  7339. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7340. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7341. * curveA and curveB keep unchanged.
  7342. */
  7343. Curve3.prototype.continue = function (curve) {
  7344. var lastPoint = this._points[this._points.length - 1];
  7345. var continuedPoints = this._points.slice();
  7346. var curvePoints = curve.getPoints();
  7347. for (var i = 1; i < curvePoints.length; i++) {
  7348. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7349. }
  7350. var continuedCurve = new Curve3(continuedPoints);
  7351. return continuedCurve;
  7352. };
  7353. Curve3.prototype._computeLength = function (path) {
  7354. var l = 0;
  7355. for (var i = 1; i < path.length; i++) {
  7356. l += (path[i].subtract(path[i - 1])).length();
  7357. }
  7358. return l;
  7359. };
  7360. return Curve3;
  7361. }());
  7362. BABYLON.Curve3 = Curve3;
  7363. // Vertex formats
  7364. var PositionNormalVertex = /** @class */ (function () {
  7365. function PositionNormalVertex(position, normal) {
  7366. if (position === void 0) { position = Vector3.Zero(); }
  7367. if (normal === void 0) { normal = Vector3.Up(); }
  7368. this.position = position;
  7369. this.normal = normal;
  7370. }
  7371. PositionNormalVertex.prototype.clone = function () {
  7372. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7373. };
  7374. return PositionNormalVertex;
  7375. }());
  7376. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7377. var PositionNormalTextureVertex = /** @class */ (function () {
  7378. function PositionNormalTextureVertex(position, normal, uv) {
  7379. if (position === void 0) { position = Vector3.Zero(); }
  7380. if (normal === void 0) { normal = Vector3.Up(); }
  7381. if (uv === void 0) { uv = Vector2.Zero(); }
  7382. this.position = position;
  7383. this.normal = normal;
  7384. this.uv = uv;
  7385. }
  7386. PositionNormalTextureVertex.prototype.clone = function () {
  7387. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7388. };
  7389. return PositionNormalTextureVertex;
  7390. }());
  7391. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7392. // Temporary pre-allocated objects for engine internal use
  7393. // usage in any internal function :
  7394. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7395. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7396. var Tmp = /** @class */ (function () {
  7397. function Tmp() {
  7398. }
  7399. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7400. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7401. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7402. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7403. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7404. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7405. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7406. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7407. Matrix.Zero(), Matrix.Zero(),
  7408. Matrix.Zero(), Matrix.Zero(),
  7409. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7410. return Tmp;
  7411. }());
  7412. BABYLON.Tmp = Tmp;
  7413. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7414. var MathTmp = /** @class */ (function () {
  7415. function MathTmp() {
  7416. }
  7417. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7418. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7419. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7420. return MathTmp;
  7421. }());
  7422. })(BABYLON || (BABYLON = {}));
  7423. //# sourceMappingURL=babylon.math.js.map
  7424. var BABYLON;
  7425. (function (BABYLON) {
  7426. var Scalar = /** @class */ (function () {
  7427. function Scalar() {
  7428. }
  7429. /**
  7430. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7431. */
  7432. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7433. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7434. var num = a - b;
  7435. return -epsilon <= num && num <= epsilon;
  7436. };
  7437. /**
  7438. * Returns a string : the upper case translation of the number i to hexadecimal.
  7439. */
  7440. Scalar.ToHex = function (i) {
  7441. var str = i.toString(16);
  7442. if (i <= 15) {
  7443. return ("0" + str).toUpperCase();
  7444. }
  7445. return str.toUpperCase();
  7446. };
  7447. /**
  7448. * Returns -1 if value is negative and +1 is value is positive.
  7449. * Returns the value itself if it's equal to zero.
  7450. */
  7451. Scalar.Sign = function (value) {
  7452. value = +value; // convert to a number
  7453. if (value === 0 || isNaN(value))
  7454. return value;
  7455. return value > 0 ? 1 : -1;
  7456. };
  7457. /**
  7458. * Returns the value itself if it's between min and max.
  7459. * Returns min if the value is lower than min.
  7460. * Returns max if the value is greater than max.
  7461. */
  7462. Scalar.Clamp = function (value, min, max) {
  7463. if (min === void 0) { min = 0; }
  7464. if (max === void 0) { max = 1; }
  7465. return Math.min(max, Math.max(min, value));
  7466. };
  7467. /**
  7468. * Returns the log2 of value.
  7469. */
  7470. Scalar.Log2 = function (value) {
  7471. return Math.log(value) * Math.LOG2E;
  7472. };
  7473. /**
  7474. * Loops the value, so that it is never larger than length and never smaller than 0.
  7475. *
  7476. * This is similar to the modulo operator but it works with floating point numbers.
  7477. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7478. * With t = 5 and length = 2.5, the result would be 0.0.
  7479. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7480. */
  7481. Scalar.Repeat = function (value, length) {
  7482. return value - Math.floor(value / length) * length;
  7483. };
  7484. /**
  7485. * Normalize the value between 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Normalize = function (value, min, max) {
  7488. return (value - min) / (max - min);
  7489. };
  7490. /**
  7491. * Denormalize the value from 0.0 and 1.0 using min and max values
  7492. */
  7493. Scalar.Denormalize = function (normalized, min, max) {
  7494. return (normalized * (max - min) + min);
  7495. };
  7496. /**
  7497. * Calculates the shortest difference between two given angles given in degrees.
  7498. */
  7499. Scalar.DeltaAngle = function (current, target) {
  7500. var num = Scalar.Repeat(target - current, 360.0);
  7501. if (num > 180.0) {
  7502. num -= 360.0;
  7503. }
  7504. return num;
  7505. };
  7506. /**
  7507. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7508. *
  7509. * The returned value will move back and forth between 0 and length
  7510. */
  7511. Scalar.PingPong = function (tx, length) {
  7512. var t = Scalar.Repeat(tx, length * 2.0);
  7513. return length - Math.abs(t - length);
  7514. };
  7515. /**
  7516. * Interpolates between min and max with smoothing at the limits.
  7517. *
  7518. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7519. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7520. */
  7521. Scalar.SmoothStep = function (from, to, tx) {
  7522. var t = Scalar.Clamp(tx);
  7523. t = -2.0 * t * t * t + 3.0 * t * t;
  7524. return to * t + from * (1.0 - t);
  7525. };
  7526. /**
  7527. * Moves a value current towards target.
  7528. *
  7529. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7530. * Negative values of maxDelta pushes the value away from target.
  7531. */
  7532. Scalar.MoveTowards = function (current, target, maxDelta) {
  7533. var result = 0;
  7534. if (Math.abs(target - current) <= maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. result = current + Scalar.Sign(target - current) * maxDelta;
  7539. }
  7540. return result;
  7541. };
  7542. /**
  7543. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7544. *
  7545. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7546. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7547. */
  7548. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7549. var num = Scalar.DeltaAngle(current, target);
  7550. var result = 0;
  7551. if (-maxDelta < num && num < maxDelta) {
  7552. result = target;
  7553. }
  7554. else {
  7555. target = current + num;
  7556. result = Scalar.MoveTowards(current, target, maxDelta);
  7557. }
  7558. return result;
  7559. };
  7560. /**
  7561. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7562. */
  7563. Scalar.Lerp = function (start, end, amount) {
  7564. return start + ((end - start) * amount);
  7565. };
  7566. /**
  7567. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7568. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7569. */
  7570. Scalar.LerpAngle = function (start, end, amount) {
  7571. var num = Scalar.Repeat(end - start, 360.0);
  7572. if (num > 180.0) {
  7573. num -= 360.0;
  7574. }
  7575. return start + num * Scalar.Clamp(amount);
  7576. };
  7577. /**
  7578. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7579. */
  7580. Scalar.InverseLerp = function (a, b, value) {
  7581. var result = 0;
  7582. if (a != b) {
  7583. result = Scalar.Clamp((value - a) / (b - a));
  7584. }
  7585. else {
  7586. result = 0.0;
  7587. }
  7588. return result;
  7589. };
  7590. /**
  7591. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7592. */
  7593. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7594. var squared = amount * amount;
  7595. var cubed = amount * squared;
  7596. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7597. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7598. var part3 = (cubed - (2.0 * squared)) + amount;
  7599. var part4 = cubed - squared;
  7600. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7601. };
  7602. /**
  7603. * Returns a random float number between and min and max values
  7604. */
  7605. Scalar.RandomRange = function (min, max) {
  7606. if (min === max)
  7607. return min;
  7608. return ((Math.random() * (max - min)) + min);
  7609. };
  7610. /**
  7611. * This function returns percentage of a number in a given range.
  7612. *
  7613. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7614. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7615. */
  7616. Scalar.RangeToPercent = function (number, min, max) {
  7617. return ((number - min) / (max - min));
  7618. };
  7619. /**
  7620. * This function returns number that corresponds to the percentage in a given range.
  7621. *
  7622. * PercentToRange(0.34,0,100) will return 34.
  7623. */
  7624. Scalar.PercentToRange = function (percent, min, max) {
  7625. return ((max - min) * percent + min);
  7626. };
  7627. /**
  7628. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7629. * @param angle The angle to normalize in radian.
  7630. * @return The converted angle.
  7631. */
  7632. Scalar.NormalizeRadians = function (angle) {
  7633. // More precise but slower version kept for reference.
  7634. // angle = angle % Tools.TwoPi;
  7635. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7636. //if (angle > Math.PI) {
  7637. // angle -= Tools.TwoPi;
  7638. //}
  7639. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7640. return angle;
  7641. };
  7642. /**
  7643. * Two pi constants convenient for computation.
  7644. */
  7645. Scalar.TwoPi = Math.PI * 2;
  7646. return Scalar;
  7647. }());
  7648. BABYLON.Scalar = Scalar;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.math.scalar.js.map
  7651. //# sourceMappingURL=babylon.mixins.js.map
  7652. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7653. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7654. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7655. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7656. //# sourceMappingURL=babylon.webgl2.js.map
  7657. var BABYLON;
  7658. (function (BABYLON) {
  7659. var __decoratorInitialStore = {};
  7660. var __mergedStore = {};
  7661. var _copySource = function (creationFunction, source, instanciate) {
  7662. var destination = creationFunction();
  7663. // Tags
  7664. if (BABYLON.Tags) {
  7665. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7666. }
  7667. var classStore = getMergedStore(destination);
  7668. // Properties
  7669. for (var property in classStore) {
  7670. var propertyDescriptor = classStore[property];
  7671. var sourceProperty = source[property];
  7672. var propertyType = propertyDescriptor.type;
  7673. if (sourceProperty !== undefined && sourceProperty !== null) {
  7674. switch (propertyType) {
  7675. case 0: // Value
  7676. case 6: // Mesh reference
  7677. case 11: // Camera reference
  7678. destination[property] = sourceProperty;
  7679. break;
  7680. case 1: // Texture
  7681. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7682. break;
  7683. case 2: // Color3
  7684. case 3: // FresnelParameters
  7685. case 4: // Vector2
  7686. case 5: // Vector3
  7687. case 7: // Color Curves
  7688. case 10: // Quaternion
  7689. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7690. break;
  7691. }
  7692. }
  7693. }
  7694. return destination;
  7695. };
  7696. function getDirectStore(target) {
  7697. var classKey = target.getClassName();
  7698. if (!__decoratorInitialStore[classKey]) {
  7699. __decoratorInitialStore[classKey] = {};
  7700. }
  7701. return __decoratorInitialStore[classKey];
  7702. }
  7703. /**
  7704. * Return the list of properties flagged as serializable
  7705. * @param target: host object
  7706. */
  7707. function getMergedStore(target) {
  7708. var classKey = target.getClassName();
  7709. if (__mergedStore[classKey]) {
  7710. return __mergedStore[classKey];
  7711. }
  7712. __mergedStore[classKey] = {};
  7713. var store = __mergedStore[classKey];
  7714. var currentTarget = target;
  7715. var currentKey = classKey;
  7716. while (currentKey) {
  7717. var initialStore = __decoratorInitialStore[currentKey];
  7718. for (var property in initialStore) {
  7719. store[property] = initialStore[property];
  7720. }
  7721. var parent_1 = void 0;
  7722. var done = false;
  7723. do {
  7724. parent_1 = Object.getPrototypeOf(currentTarget);
  7725. if (!parent_1.getClassName) {
  7726. done = true;
  7727. break;
  7728. }
  7729. if (parent_1.getClassName() !== currentKey) {
  7730. break;
  7731. }
  7732. currentTarget = parent_1;
  7733. } while (parent_1);
  7734. if (done) {
  7735. break;
  7736. }
  7737. currentKey = parent_1.getClassName();
  7738. currentTarget = parent_1;
  7739. }
  7740. return store;
  7741. }
  7742. function generateSerializableMember(type, sourceName) {
  7743. return function (target, propertyKey) {
  7744. var classStore = getDirectStore(target);
  7745. if (!classStore[propertyKey]) {
  7746. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7747. }
  7748. };
  7749. }
  7750. function generateExpandMember(setCallback, targetKey) {
  7751. if (targetKey === void 0) { targetKey = null; }
  7752. return function (target, propertyKey) {
  7753. var key = targetKey || ("_" + propertyKey);
  7754. Object.defineProperty(target, propertyKey, {
  7755. get: function () {
  7756. return this[key];
  7757. },
  7758. set: function (value) {
  7759. if (this[key] === value) {
  7760. return;
  7761. }
  7762. this[key] = value;
  7763. target[setCallback].apply(this);
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. };
  7769. }
  7770. function expandToProperty(callback, targetKey) {
  7771. if (targetKey === void 0) { targetKey = null; }
  7772. return generateExpandMember(callback, targetKey);
  7773. }
  7774. BABYLON.expandToProperty = expandToProperty;
  7775. function serialize(sourceName) {
  7776. return generateSerializableMember(0, sourceName); // value member
  7777. }
  7778. BABYLON.serialize = serialize;
  7779. function serializeAsTexture(sourceName) {
  7780. return generateSerializableMember(1, sourceName); // texture member
  7781. }
  7782. BABYLON.serializeAsTexture = serializeAsTexture;
  7783. function serializeAsColor3(sourceName) {
  7784. return generateSerializableMember(2, sourceName); // color3 member
  7785. }
  7786. BABYLON.serializeAsColor3 = serializeAsColor3;
  7787. function serializeAsFresnelParameters(sourceName) {
  7788. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7789. }
  7790. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7791. function serializeAsVector2(sourceName) {
  7792. return generateSerializableMember(4, sourceName); // vector2 member
  7793. }
  7794. BABYLON.serializeAsVector2 = serializeAsVector2;
  7795. function serializeAsVector3(sourceName) {
  7796. return generateSerializableMember(5, sourceName); // vector3 member
  7797. }
  7798. BABYLON.serializeAsVector3 = serializeAsVector3;
  7799. function serializeAsMeshReference(sourceName) {
  7800. return generateSerializableMember(6, sourceName); // mesh reference member
  7801. }
  7802. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7803. function serializeAsColorCurves(sourceName) {
  7804. return generateSerializableMember(7, sourceName); // color curves
  7805. }
  7806. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7807. function serializeAsColor4(sourceName) {
  7808. return generateSerializableMember(8, sourceName); // color 4
  7809. }
  7810. BABYLON.serializeAsColor4 = serializeAsColor4;
  7811. function serializeAsImageProcessingConfiguration(sourceName) {
  7812. return generateSerializableMember(9, sourceName); // image processing
  7813. }
  7814. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7815. function serializeAsQuaternion(sourceName) {
  7816. return generateSerializableMember(10, sourceName); // quaternion member
  7817. }
  7818. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7819. /**
  7820. * Decorator used to define property that can be serialized as reference to a camera
  7821. * @param sourceName defines the name of the property to decorate
  7822. */
  7823. function serializeAsCameraReference(sourceName) {
  7824. return generateSerializableMember(11, sourceName); // camera reference member
  7825. }
  7826. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7827. var SerializationHelper = /** @class */ (function () {
  7828. function SerializationHelper() {
  7829. }
  7830. SerializationHelper.Serialize = function (entity, serializationObject) {
  7831. if (!serializationObject) {
  7832. serializationObject = {};
  7833. }
  7834. // Tags
  7835. if (BABYLON.Tags) {
  7836. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7837. }
  7838. var serializedProperties = getMergedStore(entity);
  7839. // Properties
  7840. for (var property in serializedProperties) {
  7841. var propertyDescriptor = serializedProperties[property];
  7842. var targetPropertyName = propertyDescriptor.sourceName || property;
  7843. var propertyType = propertyDescriptor.type;
  7844. var sourceProperty = entity[property];
  7845. if (sourceProperty !== undefined && sourceProperty !== null) {
  7846. switch (propertyType) {
  7847. case 0: // Value
  7848. serializationObject[targetPropertyName] = sourceProperty;
  7849. break;
  7850. case 1: // Texture
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 2: // Color3
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 3: // FresnelParameters
  7857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7858. break;
  7859. case 4: // Vector2
  7860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7861. break;
  7862. case 5: // Vector3
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 6: // Mesh reference
  7866. serializationObject[targetPropertyName] = sourceProperty.id;
  7867. break;
  7868. case 7: // Color Curves
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 8: // Color 4
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 9: // Image Processing
  7875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7876. break;
  7877. case 10: // Quaternion
  7878. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7879. break;
  7880. case 11: // Camera reference
  7881. serializationObject[targetPropertyName] = sourceProperty.id;
  7882. break;
  7883. }
  7884. }
  7885. }
  7886. return serializationObject;
  7887. };
  7888. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7889. if (rootUrl === void 0) { rootUrl = null; }
  7890. var destination = creationFunction();
  7891. if (!rootUrl) {
  7892. rootUrl = "";
  7893. }
  7894. // Tags
  7895. if (BABYLON.Tags) {
  7896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7897. }
  7898. var classStore = getMergedStore(destination);
  7899. // Properties
  7900. for (var property in classStore) {
  7901. var propertyDescriptor = classStore[property];
  7902. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7903. var propertyType = propertyDescriptor.type;
  7904. if (sourceProperty !== undefined && sourceProperty !== null) {
  7905. var dest = destination;
  7906. switch (propertyType) {
  7907. case 0: // Value
  7908. dest[property] = sourceProperty;
  7909. break;
  7910. case 1: // Texture
  7911. if (scene) {
  7912. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7913. }
  7914. break;
  7915. case 2: // Color3
  7916. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7917. break;
  7918. case 3: // FresnelParameters
  7919. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7920. break;
  7921. case 4: // Vector2
  7922. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7923. break;
  7924. case 5: // Vector3
  7925. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7926. break;
  7927. case 6: // Mesh reference
  7928. if (scene) {
  7929. dest[property] = scene.getLastMeshByID(sourceProperty);
  7930. }
  7931. break;
  7932. case 7: // Color Curves
  7933. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7934. break;
  7935. case 8: // Color 4
  7936. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7937. break;
  7938. case 9: // Image Processing
  7939. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7940. break;
  7941. case 10: // Quaternion
  7942. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7943. break;
  7944. case 11: // Camera reference
  7945. if (scene) {
  7946. dest[property] = scene.getCameraByID(sourceProperty);
  7947. }
  7948. break;
  7949. }
  7950. }
  7951. }
  7952. return destination;
  7953. };
  7954. SerializationHelper.Clone = function (creationFunction, source) {
  7955. return _copySource(creationFunction, source, false);
  7956. };
  7957. SerializationHelper.Instanciate = function (creationFunction, source) {
  7958. return _copySource(creationFunction, source, true);
  7959. };
  7960. return SerializationHelper;
  7961. }());
  7962. BABYLON.SerializationHelper = SerializationHelper;
  7963. })(BABYLON || (BABYLON = {}));
  7964. //# sourceMappingURL=babylon.decorators.js.map
  7965. var BABYLON;
  7966. (function (BABYLON) {
  7967. /**
  7968. * Wrapper class for promise with external resolve and reject.
  7969. */
  7970. var Deferred = /** @class */ (function () {
  7971. /**
  7972. * Constructor for this deferred object.
  7973. */
  7974. function Deferred() {
  7975. var _this = this;
  7976. this.promise = new Promise(function (resolve, reject) {
  7977. _this._resolve = resolve;
  7978. _this._reject = reject;
  7979. });
  7980. }
  7981. Object.defineProperty(Deferred.prototype, "resolve", {
  7982. /**
  7983. * The resolve method of the promise associated with this deferred object.
  7984. */
  7985. get: function () {
  7986. return this._resolve;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Deferred.prototype, "reject", {
  7992. /**
  7993. * The reject method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._reject;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. return Deferred;
  8002. }());
  8003. BABYLON.Deferred = Deferred;
  8004. })(BABYLON || (BABYLON = {}));
  8005. //# sourceMappingURL=babylon.deferred.js.map
  8006. var BABYLON;
  8007. (function (BABYLON) {
  8008. /**
  8009. * A class serves as a medium between the observable and its observers
  8010. */
  8011. var EventState = /** @class */ (function () {
  8012. /**
  8013. * Create a new EventState
  8014. * @param mask defines the mask associated with this state
  8015. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8016. * @param target defines the original target of the state
  8017. * @param currentTarget defines the current target of the state
  8018. */
  8019. function EventState(mask, skipNextObservers, target, currentTarget) {
  8020. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8021. this.initalize(mask, skipNextObservers, target, currentTarget);
  8022. }
  8023. /**
  8024. * Initialize the current event state
  8025. * @param mask defines the mask associated with this state
  8026. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8027. * @param target defines the original target of the state
  8028. * @param currentTarget defines the current target of the state
  8029. * @returns the current event state
  8030. */
  8031. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8032. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8033. this.mask = mask;
  8034. this.skipNextObservers = skipNextObservers;
  8035. this.target = target;
  8036. this.currentTarget = currentTarget;
  8037. return this;
  8038. };
  8039. return EventState;
  8040. }());
  8041. BABYLON.EventState = EventState;
  8042. /**
  8043. * Represent an Observer registered to a given Observable object.
  8044. */
  8045. var Observer = /** @class */ (function () {
  8046. /**
  8047. * Creates a new observer
  8048. * @param callback defines the callback to call when the observer is notified
  8049. * @param mask defines the mask of the observer (used to filter notifications)
  8050. * @param scope defines the current scope used to restore the JS context
  8051. */
  8052. function Observer(
  8053. /**
  8054. * Defines the callback to call when the observer is notified
  8055. */
  8056. callback,
  8057. /**
  8058. * Defines the mask of the observer (used to filter notifications)
  8059. */
  8060. mask,
  8061. /**
  8062. * Defines the current scope used to restore the JS context
  8063. */
  8064. scope) {
  8065. if (scope === void 0) { scope = null; }
  8066. this.callback = callback;
  8067. this.mask = mask;
  8068. this.scope = scope;
  8069. /** @hidden */
  8070. this._willBeUnregistered = false;
  8071. /**
  8072. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8073. */
  8074. this.unregisterOnNextCall = false;
  8075. }
  8076. return Observer;
  8077. }());
  8078. BABYLON.Observer = Observer;
  8079. /**
  8080. * Represent a list of observers registered to multiple Observables object.
  8081. */
  8082. var MultiObserver = /** @class */ (function () {
  8083. function MultiObserver() {
  8084. }
  8085. /**
  8086. * Release associated resources
  8087. */
  8088. MultiObserver.prototype.dispose = function () {
  8089. if (this._observers && this._observables) {
  8090. for (var index = 0; index < this._observers.length; index++) {
  8091. this._observables[index].remove(this._observers[index]);
  8092. }
  8093. }
  8094. this._observers = null;
  8095. this._observables = null;
  8096. };
  8097. /**
  8098. * Raise a callback when one of the observable will notify
  8099. * @param observables defines a list of observables to watch
  8100. * @param callback defines the callback to call on notification
  8101. * @param mask defines the mask used to filter notifications
  8102. * @param scope defines the current scope used to restore the JS context
  8103. * @returns the new MultiObserver
  8104. */
  8105. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8106. if (mask === void 0) { mask = -1; }
  8107. if (scope === void 0) { scope = null; }
  8108. var result = new MultiObserver();
  8109. result._observers = new Array();
  8110. result._observables = observables;
  8111. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8112. var observable = observables_1[_i];
  8113. var observer = observable.add(callback, mask, false, scope);
  8114. if (observer) {
  8115. result._observers.push(observer);
  8116. }
  8117. }
  8118. return result;
  8119. };
  8120. return MultiObserver;
  8121. }());
  8122. BABYLON.MultiObserver = MultiObserver;
  8123. /**
  8124. * The Observable class is a simple implementation of the Observable pattern.
  8125. *
  8126. * 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.
  8127. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8128. * 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).
  8129. * 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.
  8130. */
  8131. var Observable = /** @class */ (function () {
  8132. /**
  8133. * Creates a new observable
  8134. * @param onObserverAdded defines a callback to call when a new observer is added
  8135. */
  8136. function Observable(onObserverAdded) {
  8137. this._observers = new Array();
  8138. this._eventState = new EventState(0);
  8139. if (onObserverAdded) {
  8140. this._onObserverAdded = onObserverAdded;
  8141. }
  8142. }
  8143. /**
  8144. * Create a new Observer with the specified callback
  8145. * @param callback the callback that will be executed for that Observer
  8146. * @param mask the mask used to filter observers
  8147. * @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.
  8148. * @param scope optional scope for the callback to be called from
  8149. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8150. * @returns the new observer created for the callback
  8151. */
  8152. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8153. if (mask === void 0) { mask = -1; }
  8154. if (insertFirst === void 0) { insertFirst = false; }
  8155. if (scope === void 0) { scope = null; }
  8156. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8157. if (!callback) {
  8158. return null;
  8159. }
  8160. var observer = new Observer(callback, mask, scope);
  8161. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8162. if (insertFirst) {
  8163. this._observers.unshift(observer);
  8164. }
  8165. else {
  8166. this._observers.push(observer);
  8167. }
  8168. if (this._onObserverAdded) {
  8169. this._onObserverAdded(observer);
  8170. }
  8171. return observer;
  8172. };
  8173. /**
  8174. * Create a new Observer with the specified callback and unregisters after the next notification
  8175. * @param callback the callback that will be executed for that Observer
  8176. * @returns the new observer created for the callback
  8177. */
  8178. Observable.prototype.addOnce = function (callback) {
  8179. return this.add(callback, undefined, undefined, undefined, true);
  8180. };
  8181. /**
  8182. * Remove an Observer from the Observable object
  8183. * @param observer the instance of the Observer to remove
  8184. * @returns false if it doesn't belong to this Observable
  8185. */
  8186. Observable.prototype.remove = function (observer) {
  8187. if (!observer) {
  8188. return false;
  8189. }
  8190. var index = this._observers.indexOf(observer);
  8191. if (index !== -1) {
  8192. this._deferUnregister(observer);
  8193. return true;
  8194. }
  8195. return false;
  8196. };
  8197. /**
  8198. * Remove a callback from the Observable object
  8199. * @param callback the callback to remove
  8200. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8201. * @returns false if it doesn't belong to this Observable
  8202. */
  8203. Observable.prototype.removeCallback = function (callback, scope) {
  8204. for (var index = 0; index < this._observers.length; index++) {
  8205. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8206. this._deferUnregister(this._observers[index]);
  8207. return true;
  8208. }
  8209. }
  8210. return false;
  8211. };
  8212. Observable.prototype._deferUnregister = function (observer) {
  8213. var _this = this;
  8214. observer.unregisterOnNextCall = false;
  8215. observer._willBeUnregistered = true;
  8216. BABYLON.Tools.SetImmediate(function () {
  8217. _this._remove(observer);
  8218. });
  8219. };
  8220. // This should only be called when not iterating over _observers to avoid callback skipping.
  8221. // Removes an observer from the _observer Array.
  8222. Observable.prototype._remove = function (observer) {
  8223. if (!observer) {
  8224. return false;
  8225. }
  8226. var index = this._observers.indexOf(observer);
  8227. if (index !== -1) {
  8228. this._observers.splice(index, 1);
  8229. return true;
  8230. }
  8231. return false;
  8232. };
  8233. /**
  8234. * Notify all Observers by calling their respective callback with the given data
  8235. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8236. * @param eventData defines the data to send to all observers
  8237. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8238. * @param target defines the original target of the state
  8239. * @param currentTarget defines the current target of the state
  8240. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8241. */
  8242. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8243. if (mask === void 0) { mask = -1; }
  8244. if (!this._observers.length) {
  8245. return true;
  8246. }
  8247. var state = this._eventState;
  8248. state.mask = mask;
  8249. state.target = target;
  8250. state.currentTarget = currentTarget;
  8251. state.skipNextObservers = false;
  8252. state.lastReturnValue = eventData;
  8253. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8254. var obs = _a[_i];
  8255. if (obs._willBeUnregistered) {
  8256. continue;
  8257. }
  8258. if (obs.mask & mask) {
  8259. if (obs.scope) {
  8260. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8261. }
  8262. else {
  8263. state.lastReturnValue = obs.callback(eventData, state);
  8264. }
  8265. if (obs.unregisterOnNextCall) {
  8266. this._deferUnregister(obs);
  8267. }
  8268. }
  8269. if (state.skipNextObservers) {
  8270. return false;
  8271. }
  8272. }
  8273. return true;
  8274. };
  8275. /**
  8276. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8277. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8278. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8279. * and it is crucial that all callbacks will be executed.
  8280. * The order of the callbacks is kept, callbacks are not executed parallel.
  8281. *
  8282. * @param eventData The data to be sent to each callback
  8283. * @param mask is used to filter observers defaults to -1
  8284. * @param target defines the callback target (see EventState)
  8285. * @param currentTarget defines he current object in the bubbling phase
  8286. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8287. */
  8288. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8289. var _this = this;
  8290. if (mask === void 0) { mask = -1; }
  8291. // create an empty promise
  8292. var p = Promise.resolve(eventData);
  8293. // no observers? return this promise.
  8294. if (!this._observers.length) {
  8295. return p;
  8296. }
  8297. var state = this._eventState;
  8298. state.mask = mask;
  8299. state.target = target;
  8300. state.currentTarget = currentTarget;
  8301. state.skipNextObservers = false;
  8302. // execute one callback after another (not using Promise.all, the order is important)
  8303. this._observers.forEach(function (obs) {
  8304. if (state.skipNextObservers) {
  8305. return;
  8306. }
  8307. if (obs._willBeUnregistered) {
  8308. return;
  8309. }
  8310. if (obs.mask & mask) {
  8311. if (obs.scope) {
  8312. p = p.then(function (lastReturnedValue) {
  8313. state.lastReturnValue = lastReturnedValue;
  8314. return obs.callback.apply(obs.scope, [eventData, state]);
  8315. });
  8316. }
  8317. else {
  8318. p = p.then(function (lastReturnedValue) {
  8319. state.lastReturnValue = lastReturnedValue;
  8320. return obs.callback(eventData, state);
  8321. });
  8322. }
  8323. if (obs.unregisterOnNextCall) {
  8324. _this._deferUnregister(obs);
  8325. }
  8326. }
  8327. });
  8328. // return the eventData
  8329. return p.then(function () { return eventData; });
  8330. };
  8331. /**
  8332. * Notify a specific observer
  8333. * @param observer defines the observer to notify
  8334. * @param eventData defines the data to be sent to each callback
  8335. * @param mask is used to filter observers defaults to -1
  8336. */
  8337. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8338. if (mask === void 0) { mask = -1; }
  8339. var state = this._eventState;
  8340. state.mask = mask;
  8341. state.skipNextObservers = false;
  8342. observer.callback(eventData, state);
  8343. };
  8344. /**
  8345. * Gets a boolean indicating if the observable has at least one observer
  8346. * @returns true is the Observable has at least one Observer registered
  8347. */
  8348. Observable.prototype.hasObservers = function () {
  8349. return this._observers.length > 0;
  8350. };
  8351. /**
  8352. * Clear the list of observers
  8353. */
  8354. Observable.prototype.clear = function () {
  8355. this._observers = new Array();
  8356. this._onObserverAdded = null;
  8357. };
  8358. /**
  8359. * Clone the current observable
  8360. * @returns a new observable
  8361. */
  8362. Observable.prototype.clone = function () {
  8363. var result = new Observable();
  8364. result._observers = this._observers.slice(0);
  8365. return result;
  8366. };
  8367. /**
  8368. * Does this observable handles observer registered with a given mask
  8369. * @param mask defines the mask to be tested
  8370. * @return whether or not one observer registered with the given mask is handeled
  8371. **/
  8372. Observable.prototype.hasSpecificMask = function (mask) {
  8373. if (mask === void 0) { mask = -1; }
  8374. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8375. var obs = _a[_i];
  8376. if (obs.mask & mask || obs.mask === mask) {
  8377. return true;
  8378. }
  8379. }
  8380. return false;
  8381. };
  8382. return Observable;
  8383. }());
  8384. BABYLON.Observable = Observable;
  8385. })(BABYLON || (BABYLON = {}));
  8386. //# sourceMappingURL=babylon.observable.js.map
  8387. var BABYLON;
  8388. (function (BABYLON) {
  8389. var SmartArray = /** @class */ (function () {
  8390. function SmartArray(capacity) {
  8391. this.length = 0;
  8392. this.data = new Array(capacity);
  8393. this._id = SmartArray._GlobalId++;
  8394. }
  8395. SmartArray.prototype.push = function (value) {
  8396. this.data[this.length++] = value;
  8397. if (this.length > this.data.length) {
  8398. this.data.length *= 2;
  8399. }
  8400. };
  8401. SmartArray.prototype.forEach = function (func) {
  8402. for (var index = 0; index < this.length; index++) {
  8403. func(this.data[index]);
  8404. }
  8405. };
  8406. SmartArray.prototype.sort = function (compareFn) {
  8407. this.data.sort(compareFn);
  8408. };
  8409. SmartArray.prototype.reset = function () {
  8410. this.length = 0;
  8411. };
  8412. SmartArray.prototype.dispose = function () {
  8413. this.reset();
  8414. if (this.data) {
  8415. this.data.length = 0;
  8416. this.data = [];
  8417. }
  8418. };
  8419. SmartArray.prototype.concat = function (array) {
  8420. if (array.length === 0) {
  8421. return;
  8422. }
  8423. if (this.length + array.length > this.data.length) {
  8424. this.data.length = (this.length + array.length) * 2;
  8425. }
  8426. for (var index = 0; index < array.length; index++) {
  8427. this.data[this.length++] = (array.data || array)[index];
  8428. }
  8429. };
  8430. SmartArray.prototype.indexOf = function (value) {
  8431. var position = this.data.indexOf(value);
  8432. if (position >= this.length) {
  8433. return -1;
  8434. }
  8435. return position;
  8436. };
  8437. SmartArray.prototype.contains = function (value) {
  8438. return this.data.indexOf(value) !== -1;
  8439. };
  8440. // Statics
  8441. SmartArray._GlobalId = 0;
  8442. return SmartArray;
  8443. }());
  8444. BABYLON.SmartArray = SmartArray;
  8445. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8446. __extends(SmartArrayNoDuplicate, _super);
  8447. function SmartArrayNoDuplicate() {
  8448. var _this = _super !== null && _super.apply(this, arguments) || this;
  8449. _this._duplicateId = 0;
  8450. return _this;
  8451. }
  8452. SmartArrayNoDuplicate.prototype.push = function (value) {
  8453. _super.prototype.push.call(this, value);
  8454. if (!value.__smartArrayFlags) {
  8455. value.__smartArrayFlags = {};
  8456. }
  8457. value.__smartArrayFlags[this._id] = this._duplicateId;
  8458. };
  8459. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8460. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8461. return false;
  8462. }
  8463. this.push(value);
  8464. return true;
  8465. };
  8466. SmartArrayNoDuplicate.prototype.reset = function () {
  8467. _super.prototype.reset.call(this);
  8468. this._duplicateId++;
  8469. };
  8470. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8471. if (array.length === 0) {
  8472. return;
  8473. }
  8474. if (this.length + array.length > this.data.length) {
  8475. this.data.length = (this.length + array.length) * 2;
  8476. }
  8477. for (var index = 0; index < array.length; index++) {
  8478. var item = (array.data || array)[index];
  8479. this.pushNoDuplicate(item);
  8480. }
  8481. };
  8482. return SmartArrayNoDuplicate;
  8483. }(SmartArray));
  8484. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8485. })(BABYLON || (BABYLON = {}));
  8486. //# sourceMappingURL=babylon.smartArray.js.map
  8487. var BABYLON;
  8488. (function (BABYLON) {
  8489. /** Class used to store color gradient */
  8490. var ColorGradient = /** @class */ (function () {
  8491. function ColorGradient() {
  8492. }
  8493. /**
  8494. * Will get a color picked randomly between color1 and color2.
  8495. * If color2 is undefined then color1 will be used
  8496. * @param result defines the target Color4 to store the result in
  8497. */
  8498. ColorGradient.prototype.getColorToRef = function (result) {
  8499. if (!this.color2) {
  8500. result.copyFrom(this.color1);
  8501. return;
  8502. }
  8503. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8504. };
  8505. return ColorGradient;
  8506. }());
  8507. BABYLON.ColorGradient = ColorGradient;
  8508. /** Class used to store factor gradient */
  8509. var FactorGradient = /** @class */ (function () {
  8510. function FactorGradient() {
  8511. }
  8512. /**
  8513. * Will get a number picked randomly between factor1 and factor2.
  8514. * If factor2 is undefined then factor1 will be used
  8515. * @returns the picked number
  8516. */
  8517. FactorGradient.prototype.getFactor = function () {
  8518. if (this.factor2 === undefined) {
  8519. return this.factor1;
  8520. }
  8521. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8522. };
  8523. return FactorGradient;
  8524. }());
  8525. BABYLON.FactorGradient = FactorGradient;
  8526. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8527. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8528. var LoadFileError = /** @class */ (function (_super) {
  8529. __extends(LoadFileError, _super);
  8530. function LoadFileError(message, request) {
  8531. var _this = _super.call(this, message) || this;
  8532. _this.request = request;
  8533. _this.name = "LoadFileError";
  8534. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8535. return _this;
  8536. }
  8537. // Polyfill for Object.setPrototypeOf if necessary.
  8538. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8539. return LoadFileError;
  8540. }(Error));
  8541. BABYLON.LoadFileError = LoadFileError;
  8542. var RetryStrategy = /** @class */ (function () {
  8543. function RetryStrategy() {
  8544. }
  8545. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8546. if (maxRetries === void 0) { maxRetries = 3; }
  8547. if (baseInterval === void 0) { baseInterval = 500; }
  8548. return function (url, request, retryIndex) {
  8549. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8550. return -1;
  8551. }
  8552. return Math.pow(2, retryIndex) * baseInterval;
  8553. };
  8554. };
  8555. return RetryStrategy;
  8556. }());
  8557. BABYLON.RetryStrategy = RetryStrategy;
  8558. // Screenshots
  8559. var screenshotCanvas;
  8560. var cloneValue = function (source, destinationObject) {
  8561. if (!source)
  8562. return null;
  8563. if (source instanceof BABYLON.Mesh) {
  8564. return null;
  8565. }
  8566. if (source instanceof BABYLON.SubMesh) {
  8567. return source.clone(destinationObject);
  8568. }
  8569. else if (source.clone) {
  8570. return source.clone();
  8571. }
  8572. return null;
  8573. };
  8574. var Tools = /** @class */ (function () {
  8575. function Tools() {
  8576. }
  8577. /**
  8578. * Interpolates between a and b via alpha
  8579. * @param a The lower value (returned when alpha = 0)
  8580. * @param b The upper value (returned when alpha = 1)
  8581. * @param alpha The interpolation-factor
  8582. * @return The mixed value
  8583. */
  8584. Tools.Mix = function (a, b, alpha) {
  8585. return a * (1 - alpha) + b * alpha;
  8586. };
  8587. Tools.Instantiate = function (className) {
  8588. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8589. return Tools.RegisteredExternalClasses[className];
  8590. }
  8591. var arr = className.split(".");
  8592. var fn = (window || this);
  8593. for (var i = 0, len = arr.length; i < len; i++) {
  8594. fn = fn[arr[i]];
  8595. }
  8596. if (typeof fn !== "function") {
  8597. return null;
  8598. }
  8599. return fn;
  8600. };
  8601. /**
  8602. * Provides a slice function that will work even on IE
  8603. * @param data defines the array to slice
  8604. * @param start defines the start of the data (optional)
  8605. * @param end defines the end of the data (optional)
  8606. * @returns the new sliced array
  8607. */
  8608. Tools.Slice = function (data, start, end) {
  8609. if (data.slice) {
  8610. return data.slice(start, end);
  8611. }
  8612. return Array.prototype.slice.call(data, start, end);
  8613. };
  8614. Tools.SetImmediate = function (action) {
  8615. if (window.setImmediate) {
  8616. window.setImmediate(action);
  8617. }
  8618. else {
  8619. setTimeout(action, 1);
  8620. }
  8621. };
  8622. Tools.IsExponentOfTwo = function (value) {
  8623. var count = 1;
  8624. do {
  8625. count *= 2;
  8626. } while (count < value);
  8627. return count === value;
  8628. };
  8629. /**
  8630. * Returns the nearest 32-bit single precision float representation of a Number
  8631. * @param value A Number. If the parameter is of a different type, it will get converted
  8632. * to a number or to NaN if it cannot be converted
  8633. * @returns number
  8634. */
  8635. Tools.FloatRound = function (value) {
  8636. if (Math.fround) {
  8637. return Math.fround(value);
  8638. }
  8639. return (Tools._tmpFloatArray[0] = value);
  8640. };
  8641. /**
  8642. * Find the next highest power of two.
  8643. * @param x Number to start search from.
  8644. * @return Next highest power of two.
  8645. */
  8646. Tools.CeilingPOT = function (x) {
  8647. x--;
  8648. x |= x >> 1;
  8649. x |= x >> 2;
  8650. x |= x >> 4;
  8651. x |= x >> 8;
  8652. x |= x >> 16;
  8653. x++;
  8654. return x;
  8655. };
  8656. /**
  8657. * Find the next lowest power of two.
  8658. * @param x Number to start search from.
  8659. * @return Next lowest power of two.
  8660. */
  8661. Tools.FloorPOT = function (x) {
  8662. x = x | (x >> 1);
  8663. x = x | (x >> 2);
  8664. x = x | (x >> 4);
  8665. x = x | (x >> 8);
  8666. x = x | (x >> 16);
  8667. return x - (x >> 1);
  8668. };
  8669. /**
  8670. * Find the nearest power of two.
  8671. * @param x Number to start search from.
  8672. * @return Next nearest power of two.
  8673. */
  8674. Tools.NearestPOT = function (x) {
  8675. var c = Tools.CeilingPOT(x);
  8676. var f = Tools.FloorPOT(x);
  8677. return (c - x) > (x - f) ? f : c;
  8678. };
  8679. Tools.GetExponentOfTwo = function (value, max, mode) {
  8680. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8681. var pot;
  8682. switch (mode) {
  8683. case BABYLON.Engine.SCALEMODE_FLOOR:
  8684. pot = Tools.FloorPOT(value);
  8685. break;
  8686. case BABYLON.Engine.SCALEMODE_NEAREST:
  8687. pot = Tools.NearestPOT(value);
  8688. break;
  8689. case BABYLON.Engine.SCALEMODE_CEILING:
  8690. default:
  8691. pot = Tools.CeilingPOT(value);
  8692. break;
  8693. }
  8694. return Math.min(pot, max);
  8695. };
  8696. Tools.GetFilename = function (path) {
  8697. var index = path.lastIndexOf("/");
  8698. if (index < 0)
  8699. return path;
  8700. return path.substring(index + 1);
  8701. };
  8702. /**
  8703. * Extracts the "folder" part of a path (everything before the filename).
  8704. * @param uri The URI to extract the info from
  8705. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8706. * @returns The "folder" part of the path
  8707. */
  8708. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8709. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8710. var index = uri.lastIndexOf("/");
  8711. if (index < 0) {
  8712. if (returnUnchangedIfNoSlash) {
  8713. return uri;
  8714. }
  8715. return "";
  8716. }
  8717. return uri.substring(0, index + 1);
  8718. };
  8719. Tools.GetDOMTextContent = function (element) {
  8720. var result = "";
  8721. var child = element.firstChild;
  8722. while (child) {
  8723. if (child.nodeType === 3) {
  8724. result += child.textContent;
  8725. }
  8726. child = child.nextSibling;
  8727. }
  8728. return result;
  8729. };
  8730. Tools.ToDegrees = function (angle) {
  8731. return angle * 180 / Math.PI;
  8732. };
  8733. Tools.ToRadians = function (angle) {
  8734. return angle * Math.PI / 180;
  8735. };
  8736. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8737. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8738. var output = "";
  8739. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8740. var i = 0;
  8741. var bytes = new Uint8Array(buffer);
  8742. while (i < bytes.length) {
  8743. chr1 = bytes[i++];
  8744. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8745. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8746. enc1 = chr1 >> 2;
  8747. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8748. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8749. enc4 = chr3 & 63;
  8750. if (isNaN(chr2)) {
  8751. enc3 = enc4 = 64;
  8752. }
  8753. else if (isNaN(chr3)) {
  8754. enc4 = 64;
  8755. }
  8756. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8757. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8758. }
  8759. return "data:image/png;base64," + output;
  8760. };
  8761. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8762. if (bias === void 0) { bias = null; }
  8763. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8764. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8765. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8766. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8767. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8768. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8769. }
  8770. if (bias) {
  8771. minimum.x -= minimum.x * bias.x + bias.y;
  8772. minimum.y -= minimum.y * bias.x + bias.y;
  8773. minimum.z -= minimum.z * bias.x + bias.y;
  8774. maximum.x += maximum.x * bias.x + bias.y;
  8775. maximum.y += maximum.y * bias.x + bias.y;
  8776. maximum.z += maximum.z * bias.x + bias.y;
  8777. }
  8778. return {
  8779. minimum: minimum,
  8780. maximum: maximum
  8781. };
  8782. };
  8783. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8784. if (bias === void 0) { bias = null; }
  8785. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8786. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8787. if (!stride) {
  8788. stride = 3;
  8789. }
  8790. for (var index = start; index < start + count; index++) {
  8791. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8792. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8793. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8794. }
  8795. if (bias) {
  8796. minimum.x -= minimum.x * bias.x + bias.y;
  8797. minimum.y -= minimum.y * bias.x + bias.y;
  8798. minimum.z -= minimum.z * bias.x + bias.y;
  8799. maximum.x += maximum.x * bias.x + bias.y;
  8800. maximum.y += maximum.y * bias.x + bias.y;
  8801. maximum.z += maximum.z * bias.x + bias.y;
  8802. }
  8803. return {
  8804. minimum: minimum,
  8805. maximum: maximum
  8806. };
  8807. };
  8808. Tools.Vector2ArrayFeeder = function (array) {
  8809. return function (index) {
  8810. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8811. var length = isFloatArray ? array.length / 2 : array.length;
  8812. if (index >= length) {
  8813. return null;
  8814. }
  8815. if (isFloatArray) {
  8816. var fa = array;
  8817. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8818. }
  8819. var a = array;
  8820. return a[index];
  8821. };
  8822. };
  8823. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8824. if (bias === void 0) { bias = null; }
  8825. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8826. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8827. var i = 0;
  8828. var cur = feeder(i++);
  8829. while (cur) {
  8830. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8831. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8832. cur = feeder(i++);
  8833. }
  8834. if (bias) {
  8835. minimum.x -= minimum.x * bias.x + bias.y;
  8836. minimum.y -= minimum.y * bias.x + bias.y;
  8837. maximum.x += maximum.x * bias.x + bias.y;
  8838. maximum.y += maximum.y * bias.x + bias.y;
  8839. }
  8840. return {
  8841. minimum: minimum,
  8842. maximum: maximum
  8843. };
  8844. };
  8845. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8846. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8847. return null;
  8848. return Array.isArray(obj) ? obj : [obj];
  8849. };
  8850. // Misc.
  8851. Tools.GetPointerPrefix = function () {
  8852. var eventPrefix = "pointer";
  8853. // Check if pointer events are supported
  8854. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8855. eventPrefix = "mouse";
  8856. }
  8857. return eventPrefix;
  8858. };
  8859. /**
  8860. * @param func - the function to be called
  8861. * @param requester - the object that will request the next frame. Falls back to window.
  8862. */
  8863. Tools.QueueNewFrame = function (func, requester) {
  8864. if (!Tools.IsWindowObjectExist()) {
  8865. return setTimeout(func, 16);
  8866. }
  8867. if (!requester) {
  8868. requester = window;
  8869. }
  8870. if (requester.requestAnimationFrame) {
  8871. return requester.requestAnimationFrame(func);
  8872. }
  8873. else if (requester.msRequestAnimationFrame) {
  8874. return requester.msRequestAnimationFrame(func);
  8875. }
  8876. else if (requester.webkitRequestAnimationFrame) {
  8877. return requester.webkitRequestAnimationFrame(func);
  8878. }
  8879. else if (requester.mozRequestAnimationFrame) {
  8880. return requester.mozRequestAnimationFrame(func);
  8881. }
  8882. else if (requester.oRequestAnimationFrame) {
  8883. return requester.oRequestAnimationFrame(func);
  8884. }
  8885. else {
  8886. return window.setTimeout(func, 16);
  8887. }
  8888. };
  8889. Tools.RequestFullscreen = function (element) {
  8890. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8891. if (!requestFunction)
  8892. return;
  8893. requestFunction.call(element);
  8894. };
  8895. Tools.ExitFullscreen = function () {
  8896. if (document.exitFullscreen) {
  8897. document.exitFullscreen();
  8898. }
  8899. else if (document.mozCancelFullScreen) {
  8900. document.mozCancelFullScreen();
  8901. }
  8902. else if (document.webkitCancelFullScreen) {
  8903. document.webkitCancelFullScreen();
  8904. }
  8905. else if (document.msCancelFullScreen) {
  8906. document.msCancelFullScreen();
  8907. }
  8908. };
  8909. Tools.SetCorsBehavior = function (url, element) {
  8910. if (url && url.indexOf("data:") === 0) {
  8911. return;
  8912. }
  8913. if (Tools.CorsBehavior) {
  8914. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8915. element.crossOrigin = Tools.CorsBehavior;
  8916. }
  8917. else {
  8918. var result = Tools.CorsBehavior(url);
  8919. if (result) {
  8920. element.crossOrigin = result;
  8921. }
  8922. }
  8923. }
  8924. };
  8925. // External files
  8926. Tools.CleanUrl = function (url) {
  8927. url = url.replace(/#/mg, "%23");
  8928. return url;
  8929. };
  8930. /**
  8931. * Loads an image as an HTMLImageElement.
  8932. * @param input url string, ArrayBuffer, or Blob to load
  8933. * @param onLoad callback called when the image successfully loads
  8934. * @param onError callback called when the image fails to load
  8935. * @param database database for caching
  8936. * @returns the HTMLImageElement of the loaded image
  8937. */
  8938. Tools.LoadImage = function (input, onLoad, onError, database) {
  8939. var url;
  8940. var usingObjectURL = false;
  8941. if (input instanceof ArrayBuffer) {
  8942. url = URL.createObjectURL(new Blob([input]));
  8943. usingObjectURL = true;
  8944. }
  8945. else if (input instanceof Blob) {
  8946. url = URL.createObjectURL(input);
  8947. usingObjectURL = true;
  8948. }
  8949. else {
  8950. url = Tools.CleanUrl(input);
  8951. url = Tools.PreprocessUrl(input);
  8952. }
  8953. var img = new Image();
  8954. Tools.SetCorsBehavior(url, img);
  8955. var loadHandler = function () {
  8956. if (usingObjectURL && img.src) {
  8957. URL.revokeObjectURL(img.src);
  8958. }
  8959. img.removeEventListener("load", loadHandler);
  8960. img.removeEventListener("error", errorHandler);
  8961. onLoad(img);
  8962. };
  8963. var errorHandler = function (err) {
  8964. if (usingObjectURL && img.src) {
  8965. URL.revokeObjectURL(img.src);
  8966. }
  8967. img.removeEventListener("load", loadHandler);
  8968. img.removeEventListener("error", errorHandler);
  8969. Tools.Error("Error while trying to load image: " + input);
  8970. if (onError) {
  8971. onError("Error while trying to load image: " + input, err);
  8972. }
  8973. };
  8974. img.addEventListener("load", loadHandler);
  8975. img.addEventListener("error", errorHandler);
  8976. var noIndexedDB = function () {
  8977. img.src = url;
  8978. };
  8979. var loadFromIndexedDB = function () {
  8980. if (database) {
  8981. database.loadImageFromDB(url, img);
  8982. }
  8983. };
  8984. //ANY database to do!
  8985. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8986. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8987. }
  8988. else {
  8989. if (url.indexOf("file:") !== -1) {
  8990. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8991. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8992. try {
  8993. var blobURL;
  8994. try {
  8995. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8996. }
  8997. catch (ex) {
  8998. // Chrome doesn't support oneTimeOnly parameter
  8999. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9000. }
  9001. img.src = blobURL;
  9002. usingObjectURL = true;
  9003. }
  9004. catch (e) {
  9005. img.src = "";
  9006. }
  9007. return img;
  9008. }
  9009. }
  9010. noIndexedDB();
  9011. }
  9012. return img;
  9013. };
  9014. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9015. url = Tools.CleanUrl(url);
  9016. url = Tools.PreprocessUrl(url);
  9017. // If file and file input are set
  9018. if (url.indexOf("file:") !== -1) {
  9019. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9020. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9021. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9022. }
  9023. }
  9024. var loadUrl = Tools.BaseUrl + url;
  9025. var aborted = false;
  9026. var fileRequest = {
  9027. onCompleteObservable: new BABYLON.Observable(),
  9028. abort: function () { return aborted = true; },
  9029. };
  9030. var requestFile = function () {
  9031. var request = new XMLHttpRequest();
  9032. var retryHandle = null;
  9033. fileRequest.abort = function () {
  9034. aborted = true;
  9035. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9036. request.abort();
  9037. }
  9038. if (retryHandle !== null) {
  9039. clearTimeout(retryHandle);
  9040. retryHandle = null;
  9041. }
  9042. };
  9043. var retryLoop = function (retryIndex) {
  9044. request.open('GET', loadUrl, true);
  9045. if (useArrayBuffer) {
  9046. request.responseType = "arraybuffer";
  9047. }
  9048. if (onProgress) {
  9049. request.addEventListener("progress", onProgress);
  9050. }
  9051. var onLoadEnd = function () {
  9052. request.removeEventListener("loadend", onLoadEnd);
  9053. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9054. fileRequest.onCompleteObservable.clear();
  9055. };
  9056. request.addEventListener("loadend", onLoadEnd);
  9057. var onReadyStateChange = function () {
  9058. if (aborted) {
  9059. return;
  9060. }
  9061. // In case of undefined state in some browsers.
  9062. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9063. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9064. request.removeEventListener("readystatechange", onReadyStateChange);
  9065. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9066. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9067. return;
  9068. }
  9069. var retryStrategy = Tools.DefaultRetryStrategy;
  9070. if (retryStrategy) {
  9071. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9072. if (waitTime !== -1) {
  9073. // Prevent the request from completing for retry.
  9074. request.removeEventListener("loadend", onLoadEnd);
  9075. request = new XMLHttpRequest();
  9076. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9077. return;
  9078. }
  9079. }
  9080. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9081. if (onError) {
  9082. onError(request, e);
  9083. }
  9084. else {
  9085. throw e;
  9086. }
  9087. }
  9088. };
  9089. request.addEventListener("readystatechange", onReadyStateChange);
  9090. request.send();
  9091. };
  9092. retryLoop(0);
  9093. };
  9094. // Caching all files
  9095. if (database && database.enableSceneOffline) {
  9096. var noIndexedDB_1 = function () {
  9097. if (!aborted) {
  9098. requestFile();
  9099. }
  9100. };
  9101. var loadFromIndexedDB = function () {
  9102. // TODO: database needs to support aborting and should return a IFileRequest
  9103. if (aborted) {
  9104. return;
  9105. }
  9106. if (database) {
  9107. database.loadFileFromDB(url, function (data) {
  9108. if (!aborted) {
  9109. onSuccess(data);
  9110. }
  9111. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9112. }, onProgress ? function (event) {
  9113. if (!aborted) {
  9114. onProgress(event);
  9115. }
  9116. } : undefined, noIndexedDB_1, useArrayBuffer);
  9117. }
  9118. };
  9119. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9120. }
  9121. else {
  9122. requestFile();
  9123. }
  9124. return fileRequest;
  9125. };
  9126. /**
  9127. * Load a script (identified by an url). When the url returns, the
  9128. * content of this file is added into a new script element, attached to the DOM (body element)
  9129. */
  9130. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9131. var head = document.getElementsByTagName('head')[0];
  9132. var script = document.createElement('script');
  9133. script.type = 'text/javascript';
  9134. script.src = scriptUrl;
  9135. script.onload = function () {
  9136. if (onSuccess) {
  9137. onSuccess();
  9138. }
  9139. };
  9140. script.onerror = function (e) {
  9141. if (onError) {
  9142. onError("Unable to load script '" + scriptUrl + "'", e);
  9143. }
  9144. };
  9145. head.appendChild(script);
  9146. };
  9147. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9148. var reader = new FileReader();
  9149. var request = {
  9150. onCompleteObservable: new BABYLON.Observable(),
  9151. abort: function () { return reader.abort(); },
  9152. };
  9153. reader.onloadend = function (e) {
  9154. request.onCompleteObservable.notifyObservers(request);
  9155. };
  9156. reader.onload = function (e) {
  9157. //target doesn't have result from ts 1.3
  9158. callback(e.target['result']);
  9159. };
  9160. reader.onprogress = progressCallback;
  9161. reader.readAsDataURL(fileToLoad);
  9162. return request;
  9163. };
  9164. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9165. var reader = new FileReader();
  9166. var request = {
  9167. onCompleteObservable: new BABYLON.Observable(),
  9168. abort: function () { return reader.abort(); },
  9169. };
  9170. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9171. reader.onerror = function (e) {
  9172. Tools.Log("Error while reading file: " + fileToLoad.name);
  9173. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9174. };
  9175. reader.onload = function (e) {
  9176. //target doesn't have result from ts 1.3
  9177. callback(e.target['result']);
  9178. };
  9179. if (progressCallBack) {
  9180. reader.onprogress = progressCallBack;
  9181. }
  9182. if (!useArrayBuffer) {
  9183. // Asynchronous read
  9184. reader.readAsText(fileToLoad);
  9185. }
  9186. else {
  9187. reader.readAsArrayBuffer(fileToLoad);
  9188. }
  9189. return request;
  9190. };
  9191. //returns a downloadable url to a file content.
  9192. Tools.FileAsURL = function (content) {
  9193. var fileBlob = new Blob([content]);
  9194. var url = window.URL || window.webkitURL;
  9195. var link = url.createObjectURL(fileBlob);
  9196. return link;
  9197. };
  9198. // Misc.
  9199. Tools.Format = function (value, decimals) {
  9200. if (decimals === void 0) { decimals = 2; }
  9201. return value.toFixed(decimals);
  9202. };
  9203. Tools.CheckExtends = function (v, min, max) {
  9204. if (v.x < min.x)
  9205. min.x = v.x;
  9206. if (v.y < min.y)
  9207. min.y = v.y;
  9208. if (v.z < min.z)
  9209. min.z = v.z;
  9210. if (v.x > max.x)
  9211. max.x = v.x;
  9212. if (v.y > max.y)
  9213. max.y = v.y;
  9214. if (v.z > max.z)
  9215. max.z = v.z;
  9216. };
  9217. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9218. for (var prop in source) {
  9219. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9220. continue;
  9221. }
  9222. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9223. continue;
  9224. }
  9225. var sourceValue = source[prop];
  9226. var typeOfSourceValue = typeof sourceValue;
  9227. if (typeOfSourceValue === "function") {
  9228. continue;
  9229. }
  9230. try {
  9231. if (typeOfSourceValue === "object") {
  9232. if (sourceValue instanceof Array) {
  9233. destination[prop] = [];
  9234. if (sourceValue.length > 0) {
  9235. if (typeof sourceValue[0] == "object") {
  9236. for (var index = 0; index < sourceValue.length; index++) {
  9237. var clonedValue = cloneValue(sourceValue[index], destination);
  9238. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9239. destination[prop].push(clonedValue);
  9240. }
  9241. }
  9242. }
  9243. else {
  9244. destination[prop] = sourceValue.slice(0);
  9245. }
  9246. }
  9247. }
  9248. else {
  9249. destination[prop] = cloneValue(sourceValue, destination);
  9250. }
  9251. }
  9252. else {
  9253. destination[prop] = sourceValue;
  9254. }
  9255. }
  9256. catch (e) {
  9257. // Just ignore error (it could be because of a read-only property)
  9258. }
  9259. }
  9260. };
  9261. Tools.IsEmpty = function (obj) {
  9262. for (var i in obj) {
  9263. if (obj.hasOwnProperty(i)) {
  9264. return false;
  9265. }
  9266. }
  9267. return true;
  9268. };
  9269. Tools.RegisterTopRootEvents = function (events) {
  9270. for (var index = 0; index < events.length; index++) {
  9271. var event = events[index];
  9272. window.addEventListener(event.name, event.handler, false);
  9273. try {
  9274. if (window.parent) {
  9275. window.parent.addEventListener(event.name, event.handler, false);
  9276. }
  9277. }
  9278. catch (e) {
  9279. // Silently fails...
  9280. }
  9281. }
  9282. };
  9283. Tools.UnregisterTopRootEvents = function (events) {
  9284. for (var index = 0; index < events.length; index++) {
  9285. var event = events[index];
  9286. window.removeEventListener(event.name, event.handler);
  9287. try {
  9288. if (window.parent) {
  9289. window.parent.removeEventListener(event.name, event.handler);
  9290. }
  9291. }
  9292. catch (e) {
  9293. // Silently fails...
  9294. }
  9295. }
  9296. };
  9297. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9298. if (mimeType === void 0) { mimeType = "image/png"; }
  9299. // Read the contents of the framebuffer
  9300. var numberOfChannelsByLine = width * 4;
  9301. var halfHeight = height / 2;
  9302. //Reading datas from WebGL
  9303. var data = engine.readPixels(0, 0, width, height);
  9304. //To flip image on Y axis.
  9305. for (var i = 0; i < halfHeight; i++) {
  9306. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9307. var currentCell = j + i * numberOfChannelsByLine;
  9308. var targetLine = height - i - 1;
  9309. var targetCell = j + targetLine * numberOfChannelsByLine;
  9310. var temp = data[currentCell];
  9311. data[currentCell] = data[targetCell];
  9312. data[targetCell] = temp;
  9313. }
  9314. }
  9315. // Create a 2D canvas to store the result
  9316. if (!screenshotCanvas) {
  9317. screenshotCanvas = document.createElement('canvas');
  9318. }
  9319. screenshotCanvas.width = width;
  9320. screenshotCanvas.height = height;
  9321. var context = screenshotCanvas.getContext('2d');
  9322. if (context) {
  9323. // Copy the pixels to a 2D canvas
  9324. var imageData = context.createImageData(width, height);
  9325. var castData = (imageData.data);
  9326. castData.set(data);
  9327. context.putImageData(imageData, 0, 0);
  9328. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9329. }
  9330. };
  9331. /**
  9332. * Converts the canvas data to blob.
  9333. * This acts as a polyfill for browsers not supporting the to blob function.
  9334. * @param canvas Defines the canvas to extract the data from
  9335. * @param successCallback Defines the callback triggered once the data are available
  9336. * @param mimeType Defines the mime type of the result
  9337. */
  9338. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9339. if (mimeType === void 0) { mimeType = "image/png"; }
  9340. // We need HTMLCanvasElement.toBlob for HD screenshots
  9341. if (!canvas.toBlob) {
  9342. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9343. canvas.toBlob = function (callback, type, quality) {
  9344. var _this = this;
  9345. setTimeout(function () {
  9346. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9347. for (var i = 0; i < len; i++) {
  9348. arr[i] = binStr.charCodeAt(i);
  9349. }
  9350. callback(new Blob([arr]));
  9351. });
  9352. };
  9353. }
  9354. canvas.toBlob(function (blob) {
  9355. successCallback(blob);
  9356. }, mimeType);
  9357. };
  9358. /**
  9359. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9360. * @param successCallback Defines the callback triggered once the data are available
  9361. * @param mimeType Defines the mime type of the result
  9362. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9363. */
  9364. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9365. if (mimeType === void 0) { mimeType = "image/png"; }
  9366. if (successCallback) {
  9367. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9368. successCallback(base64Image);
  9369. }
  9370. else {
  9371. this.ToBlob(screenshotCanvas, function (blob) {
  9372. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9373. if (("download" in document.createElement("a"))) {
  9374. if (!fileName) {
  9375. var date = new Date();
  9376. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9377. fileName = "screenshot_" + stringDate + ".png";
  9378. }
  9379. Tools.Download(blob, fileName);
  9380. }
  9381. else {
  9382. var url = URL.createObjectURL(blob);
  9383. var newWindow = window.open("");
  9384. if (!newWindow)
  9385. return;
  9386. var img = newWindow.document.createElement("img");
  9387. img.onload = function () {
  9388. // no longer need to read the blob so it's revoked
  9389. URL.revokeObjectURL(url);
  9390. };
  9391. img.src = url;
  9392. newWindow.document.body.appendChild(img);
  9393. }
  9394. }, mimeType);
  9395. }
  9396. };
  9397. /**
  9398. * Downloads a blob in the browser
  9399. * @param blob defines the blob to download
  9400. * @param fileName defines the name of the downloaded file
  9401. */
  9402. Tools.Download = function (blob, fileName) {
  9403. var url = window.URL.createObjectURL(blob);
  9404. var a = document.createElement("a");
  9405. document.body.appendChild(a);
  9406. a.style.display = "none";
  9407. a.href = url;
  9408. a.download = fileName;
  9409. a.addEventListener("click", function () {
  9410. if (a.parentElement) {
  9411. a.parentElement.removeChild(a);
  9412. }
  9413. });
  9414. a.click();
  9415. window.URL.revokeObjectURL(url);
  9416. };
  9417. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9418. if (mimeType === void 0) { mimeType = "image/png"; }
  9419. var width;
  9420. var height;
  9421. // If a precision value is specified
  9422. if (size.precision) {
  9423. width = Math.round(engine.getRenderWidth() * size.precision);
  9424. height = Math.round(width / engine.getAspectRatio(camera));
  9425. }
  9426. else if (size.width && size.height) {
  9427. width = size.width;
  9428. height = size.height;
  9429. }
  9430. //If passing only width, computing height to keep display canvas ratio.
  9431. else if (size.width && !size.height) {
  9432. width = size.width;
  9433. height = Math.round(width / engine.getAspectRatio(camera));
  9434. }
  9435. //If passing only height, computing width to keep display canvas ratio.
  9436. else if (size.height && !size.width) {
  9437. height = size.height;
  9438. width = Math.round(height * engine.getAspectRatio(camera));
  9439. }
  9440. //Assuming here that "size" parameter is a number
  9441. else if (!isNaN(size)) {
  9442. height = size;
  9443. width = size;
  9444. }
  9445. else {
  9446. Tools.Error("Invalid 'size' parameter !");
  9447. return;
  9448. }
  9449. if (!screenshotCanvas) {
  9450. screenshotCanvas = document.createElement('canvas');
  9451. }
  9452. screenshotCanvas.width = width;
  9453. screenshotCanvas.height = height;
  9454. var renderContext = screenshotCanvas.getContext("2d");
  9455. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9456. var newWidth = width;
  9457. var newHeight = newWidth / ratio;
  9458. if (newHeight > height) {
  9459. newHeight = height;
  9460. newWidth = newHeight * ratio;
  9461. }
  9462. var offsetX = Math.max(0, width - newWidth) / 2;
  9463. var offsetY = Math.max(0, height - newHeight) / 2;
  9464. var renderingCanvas = engine.getRenderingCanvas();
  9465. if (renderContext && renderingCanvas) {
  9466. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9467. }
  9468. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9469. };
  9470. /**
  9471. * Generates an image screenshot from the specified camera.
  9472. *
  9473. * @param engine The engine to use for rendering
  9474. * @param camera The camera to use for rendering
  9475. * @param size This parameter can be set to a single number or to an object with the
  9476. * following (optional) properties: precision, width, height. If a single number is passed,
  9477. * it will be used for both width and height. If an object is passed, the screenshot size
  9478. * will be derived from the parameters. The precision property is a multiplier allowing
  9479. * rendering at a higher or lower resolution.
  9480. * @param successCallback The callback receives a single parameter which contains the
  9481. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9482. * src parameter of an <img> to display it.
  9483. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9484. * Check your browser for supported MIME types.
  9485. * @param samples Texture samples (default: 1)
  9486. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9487. * @param fileName A name for for the downloaded file.
  9488. * @constructor
  9489. */
  9490. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9491. if (mimeType === void 0) { mimeType = "image/png"; }
  9492. if (samples === void 0) { samples = 1; }
  9493. if (antialiasing === void 0) { antialiasing = false; }
  9494. var width;
  9495. var height;
  9496. //If a precision value is specified
  9497. if (size.precision) {
  9498. width = Math.round(engine.getRenderWidth() * size.precision);
  9499. height = Math.round(width / engine.getAspectRatio(camera));
  9500. size = { width: width, height: height };
  9501. }
  9502. else if (size.width && size.height) {
  9503. width = size.width;
  9504. height = size.height;
  9505. }
  9506. //If passing only width, computing height to keep display canvas ratio.
  9507. else if (size.width && !size.height) {
  9508. width = size.width;
  9509. height = Math.round(width / engine.getAspectRatio(camera));
  9510. size = { width: width, height: height };
  9511. }
  9512. //If passing only height, computing width to keep display canvas ratio.
  9513. else if (size.height && !size.width) {
  9514. height = size.height;
  9515. width = Math.round(height * engine.getAspectRatio(camera));
  9516. size = { width: width, height: height };
  9517. }
  9518. //Assuming here that "size" parameter is a number
  9519. else if (!isNaN(size)) {
  9520. height = size;
  9521. width = size;
  9522. }
  9523. else {
  9524. Tools.Error("Invalid 'size' parameter !");
  9525. return;
  9526. }
  9527. var scene = camera.getScene();
  9528. var previousCamera = null;
  9529. if (scene.activeCamera !== camera) {
  9530. previousCamera = scene.activeCamera;
  9531. scene.activeCamera = camera;
  9532. }
  9533. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9534. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9535. texture.renderList = null;
  9536. texture.samples = samples;
  9537. if (antialiasing) {
  9538. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9539. }
  9540. texture.onAfterRenderObservable.add(function () {
  9541. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9542. });
  9543. scene.incrementRenderId();
  9544. scene.resetCachedMaterial();
  9545. texture.render(true);
  9546. texture.dispose();
  9547. if (previousCamera) {
  9548. scene.activeCamera = previousCamera;
  9549. }
  9550. camera.getProjectionMatrix(true); // Force cache refresh;
  9551. };
  9552. // XHR response validator for local file scenario
  9553. Tools.ValidateXHRData = function (xhr, dataType) {
  9554. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9555. if (dataType === void 0) { dataType = 7; }
  9556. try {
  9557. if (dataType & 1) {
  9558. if (xhr.responseText && xhr.responseText.length > 0) {
  9559. return true;
  9560. }
  9561. else if (dataType === 1) {
  9562. return false;
  9563. }
  9564. }
  9565. if (dataType & 2) {
  9566. // Check header width and height since there is no "TGA" magic number
  9567. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9568. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9569. return true;
  9570. }
  9571. else if (dataType === 2) {
  9572. return false;
  9573. }
  9574. }
  9575. if (dataType & 4) {
  9576. // Check for the "DDS" magic number
  9577. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9578. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9579. return true;
  9580. }
  9581. else {
  9582. return false;
  9583. }
  9584. }
  9585. }
  9586. catch (e) {
  9587. // Global protection
  9588. }
  9589. return false;
  9590. };
  9591. /**
  9592. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9593. * Be aware Math.random() could cause collisions, but:
  9594. * "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"
  9595. */
  9596. Tools.RandomId = function () {
  9597. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9598. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9599. return v.toString(16);
  9600. });
  9601. };
  9602. /**
  9603. * Test if the given uri is a base64 string.
  9604. * @param uri The uri to test
  9605. * @return True if the uri is a base64 string or false otherwise.
  9606. */
  9607. Tools.IsBase64 = function (uri) {
  9608. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9609. };
  9610. /**
  9611. * Decode the given base64 uri.
  9612. * @param uri The uri to decode
  9613. * @return The decoded base64 data.
  9614. */
  9615. Tools.DecodeBase64 = function (uri) {
  9616. var decodedString = atob(uri.split(",")[1]);
  9617. var bufferLength = decodedString.length;
  9618. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9619. for (var i = 0; i < bufferLength; i++) {
  9620. bufferView[i] = decodedString.charCodeAt(i);
  9621. }
  9622. return bufferView.buffer;
  9623. };
  9624. Object.defineProperty(Tools, "NoneLogLevel", {
  9625. get: function () {
  9626. return Tools._NoneLogLevel;
  9627. },
  9628. enumerable: true,
  9629. configurable: true
  9630. });
  9631. Object.defineProperty(Tools, "MessageLogLevel", {
  9632. get: function () {
  9633. return Tools._MessageLogLevel;
  9634. },
  9635. enumerable: true,
  9636. configurable: true
  9637. });
  9638. Object.defineProperty(Tools, "WarningLogLevel", {
  9639. get: function () {
  9640. return Tools._WarningLogLevel;
  9641. },
  9642. enumerable: true,
  9643. configurable: true
  9644. });
  9645. Object.defineProperty(Tools, "ErrorLogLevel", {
  9646. get: function () {
  9647. return Tools._ErrorLogLevel;
  9648. },
  9649. enumerable: true,
  9650. configurable: true
  9651. });
  9652. Object.defineProperty(Tools, "AllLogLevel", {
  9653. get: function () {
  9654. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9655. },
  9656. enumerable: true,
  9657. configurable: true
  9658. });
  9659. Tools._AddLogEntry = function (entry) {
  9660. Tools._LogCache = entry + Tools._LogCache;
  9661. if (Tools.OnNewCacheEntry) {
  9662. Tools.OnNewCacheEntry(entry);
  9663. }
  9664. };
  9665. Tools._FormatMessage = function (message) {
  9666. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9667. var date = new Date();
  9668. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9669. };
  9670. Tools._LogDisabled = function (message) {
  9671. // nothing to do
  9672. };
  9673. Tools._LogEnabled = function (message) {
  9674. var formattedMessage = Tools._FormatMessage(message);
  9675. console.log("BJS - " + formattedMessage);
  9676. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9677. Tools._AddLogEntry(entry);
  9678. };
  9679. Tools._WarnDisabled = function (message) {
  9680. // nothing to do
  9681. };
  9682. Tools._WarnEnabled = function (message) {
  9683. var formattedMessage = Tools._FormatMessage(message);
  9684. console.warn("BJS - " + formattedMessage);
  9685. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9686. Tools._AddLogEntry(entry);
  9687. };
  9688. Tools._ErrorDisabled = function (message) {
  9689. // nothing to do
  9690. };
  9691. Tools._ErrorEnabled = function (message) {
  9692. Tools.errorsCount++;
  9693. var formattedMessage = Tools._FormatMessage(message);
  9694. console.error("BJS - " + formattedMessage);
  9695. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9696. Tools._AddLogEntry(entry);
  9697. };
  9698. Object.defineProperty(Tools, "LogCache", {
  9699. get: function () {
  9700. return Tools._LogCache;
  9701. },
  9702. enumerable: true,
  9703. configurable: true
  9704. });
  9705. Tools.ClearLogCache = function () {
  9706. Tools._LogCache = "";
  9707. Tools.errorsCount = 0;
  9708. };
  9709. Object.defineProperty(Tools, "LogLevels", {
  9710. set: function (level) {
  9711. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9712. Tools.Log = Tools._LogEnabled;
  9713. }
  9714. else {
  9715. Tools.Log = Tools._LogDisabled;
  9716. }
  9717. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9718. Tools.Warn = Tools._WarnEnabled;
  9719. }
  9720. else {
  9721. Tools.Warn = Tools._WarnDisabled;
  9722. }
  9723. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9724. Tools.Error = Tools._ErrorEnabled;
  9725. }
  9726. else {
  9727. Tools.Error = Tools._ErrorDisabled;
  9728. }
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. Tools.IsWindowObjectExist = function () {
  9734. return (typeof window) !== "undefined";
  9735. };
  9736. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9737. get: function () {
  9738. return Tools._PerformanceNoneLogLevel;
  9739. },
  9740. enumerable: true,
  9741. configurable: true
  9742. });
  9743. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9744. get: function () {
  9745. return Tools._PerformanceUserMarkLogLevel;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9751. get: function () {
  9752. return Tools._PerformanceConsoleLogLevel;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9758. set: function (level) {
  9759. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9760. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9761. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9762. return;
  9763. }
  9764. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9765. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9766. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9767. return;
  9768. }
  9769. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9770. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9771. },
  9772. enumerable: true,
  9773. configurable: true
  9774. });
  9775. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9776. };
  9777. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9778. };
  9779. Tools._StartUserMark = function (counterName, condition) {
  9780. if (condition === void 0) { condition = true; }
  9781. if (!Tools._performance) {
  9782. if (!Tools.IsWindowObjectExist()) {
  9783. return;
  9784. }
  9785. Tools._performance = window.performance;
  9786. }
  9787. if (!condition || !Tools._performance.mark) {
  9788. return;
  9789. }
  9790. Tools._performance.mark(counterName + "-Begin");
  9791. };
  9792. Tools._EndUserMark = function (counterName, condition) {
  9793. if (condition === void 0) { condition = true; }
  9794. if (!condition || !Tools._performance.mark) {
  9795. return;
  9796. }
  9797. Tools._performance.mark(counterName + "-End");
  9798. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9799. };
  9800. Tools._StartPerformanceConsole = function (counterName, condition) {
  9801. if (condition === void 0) { condition = true; }
  9802. if (!condition) {
  9803. return;
  9804. }
  9805. Tools._StartUserMark(counterName, condition);
  9806. if (console.time) {
  9807. console.time(counterName);
  9808. }
  9809. };
  9810. Tools._EndPerformanceConsole = function (counterName, condition) {
  9811. if (condition === void 0) { condition = true; }
  9812. if (!condition) {
  9813. return;
  9814. }
  9815. Tools._EndUserMark(counterName, condition);
  9816. if (console.time) {
  9817. console.timeEnd(counterName);
  9818. }
  9819. };
  9820. Object.defineProperty(Tools, "Now", {
  9821. get: function () {
  9822. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9823. return window.performance.now();
  9824. }
  9825. return Date.now();
  9826. },
  9827. enumerable: true,
  9828. configurable: true
  9829. });
  9830. /**
  9831. * This method will return the name of the class used to create the instance of the given object.
  9832. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9833. * @param object the object to get the class name from
  9834. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9835. */
  9836. Tools.GetClassName = function (object, isType) {
  9837. if (isType === void 0) { isType = false; }
  9838. var name = null;
  9839. if (!isType && object.getClassName) {
  9840. name = object.getClassName();
  9841. }
  9842. else {
  9843. if (object instanceof Object) {
  9844. var classObj = isType ? object : Object.getPrototypeOf(object);
  9845. name = classObj.constructor["__bjsclassName__"];
  9846. }
  9847. if (!name) {
  9848. name = typeof object;
  9849. }
  9850. }
  9851. return name;
  9852. };
  9853. Tools.First = function (array, predicate) {
  9854. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9855. var el = array_1[_i];
  9856. if (predicate(el)) {
  9857. return el;
  9858. }
  9859. }
  9860. return null;
  9861. };
  9862. /**
  9863. * This method will return the name of the full name of the class, including its owning module (if any).
  9864. * 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).
  9865. * @param object the object to get the class name from
  9866. * @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.
  9867. */
  9868. Tools.getFullClassName = function (object, isType) {
  9869. if (isType === void 0) { isType = false; }
  9870. var className = null;
  9871. var moduleName = null;
  9872. if (!isType && object.getClassName) {
  9873. className = object.getClassName();
  9874. }
  9875. else {
  9876. if (object instanceof Object) {
  9877. var classObj = isType ? object : Object.getPrototypeOf(object);
  9878. className = classObj.constructor["__bjsclassName__"];
  9879. moduleName = classObj.constructor["__bjsmoduleName__"];
  9880. }
  9881. if (!className) {
  9882. className = typeof object;
  9883. }
  9884. }
  9885. if (!className) {
  9886. return null;
  9887. }
  9888. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9889. };
  9890. /**
  9891. * 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.
  9892. * @param array
  9893. */
  9894. Tools.arrayOrStringFeeder = function (array) {
  9895. return function (index) {
  9896. if (index >= array.length) {
  9897. return null;
  9898. }
  9899. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9900. if (val && val.getHashCode) {
  9901. val = val.getHashCode();
  9902. }
  9903. if (typeof val === "string") {
  9904. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9905. }
  9906. return val;
  9907. };
  9908. };
  9909. /**
  9910. * Compute the hashCode of a stream of number
  9911. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9912. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9913. * @return the hash code computed
  9914. */
  9915. Tools.hashCodeFromStream = function (feeder) {
  9916. // Based from here: http://stackoverflow.com/a/7616484/802124
  9917. var hash = 0;
  9918. var index = 0;
  9919. var chr = feeder(index++);
  9920. while (chr != null) {
  9921. hash = ((hash << 5) - hash) + chr;
  9922. hash |= 0; // Convert to 32bit integer
  9923. chr = feeder(index++);
  9924. }
  9925. return hash;
  9926. };
  9927. /**
  9928. * Returns a promise that resolves after the given amount of time.
  9929. * @param delay Number of milliseconds to delay
  9930. * @returns Promise that resolves after the given amount of time
  9931. */
  9932. Tools.DelayAsync = function (delay) {
  9933. return new Promise(function (resolve) {
  9934. setTimeout(function () {
  9935. resolve();
  9936. }, delay);
  9937. });
  9938. };
  9939. /**
  9940. * Gets the current gradient from an array of IValueGradient
  9941. * @param ratio defines the current ratio to get
  9942. * @param gradients defines the array of IValueGradient
  9943. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9944. */
  9945. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9946. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9947. var currentGradient = gradients[gradientIndex];
  9948. var nextGradient = gradients[gradientIndex + 1];
  9949. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9950. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9951. updateFunc(currentGradient, nextGradient, scale);
  9952. }
  9953. }
  9954. };
  9955. Tools.BaseUrl = "";
  9956. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9957. /**
  9958. * Default behaviour for cors in the application.
  9959. * It can be a string if the expected behavior is identical in the entire app.
  9960. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9961. */
  9962. Tools.CorsBehavior = "anonymous";
  9963. Tools.UseFallbackTexture = true;
  9964. /**
  9965. * Use this object to register external classes like custom textures or material
  9966. * to allow the laoders to instantiate them
  9967. */
  9968. Tools.RegisteredExternalClasses = {};
  9969. // Used in case of a texture loading problem
  9970. 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";
  9971. Tools._tmpFloatArray = new Float32Array(1);
  9972. Tools.PreprocessUrl = function (url) {
  9973. return url;
  9974. };
  9975. // Logs
  9976. Tools._NoneLogLevel = 0;
  9977. Tools._MessageLogLevel = 1;
  9978. Tools._WarningLogLevel = 2;
  9979. Tools._ErrorLogLevel = 4;
  9980. Tools._LogCache = "";
  9981. Tools.errorsCount = 0;
  9982. Tools.Log = Tools._LogEnabled;
  9983. Tools.Warn = Tools._WarnEnabled;
  9984. Tools.Error = Tools._ErrorEnabled;
  9985. // Performances
  9986. Tools._PerformanceNoneLogLevel = 0;
  9987. Tools._PerformanceUserMarkLogLevel = 1;
  9988. Tools._PerformanceConsoleLogLevel = 2;
  9989. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9990. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9991. return Tools;
  9992. }());
  9993. BABYLON.Tools = Tools;
  9994. /**
  9995. * This class is used to track a performance counter which is number based.
  9996. * The user has access to many properties which give statistics of different nature
  9997. *
  9998. * The implementer can track two kinds of Performance Counter: time and count
  9999. * 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.
  10000. * 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.
  10001. */
  10002. var PerfCounter = /** @class */ (function () {
  10003. function PerfCounter() {
  10004. this._startMonitoringTime = 0;
  10005. this._min = 0;
  10006. this._max = 0;
  10007. this._average = 0;
  10008. this._lastSecAverage = 0;
  10009. this._current = 0;
  10010. this._totalValueCount = 0;
  10011. this._totalAccumulated = 0;
  10012. this._lastSecAccumulated = 0;
  10013. this._lastSecTime = 0;
  10014. this._lastSecValueCount = 0;
  10015. }
  10016. Object.defineProperty(PerfCounter.prototype, "min", {
  10017. /**
  10018. * Returns the smallest value ever
  10019. */
  10020. get: function () {
  10021. return this._min;
  10022. },
  10023. enumerable: true,
  10024. configurable: true
  10025. });
  10026. Object.defineProperty(PerfCounter.prototype, "max", {
  10027. /**
  10028. * Returns the biggest value ever
  10029. */
  10030. get: function () {
  10031. return this._max;
  10032. },
  10033. enumerable: true,
  10034. configurable: true
  10035. });
  10036. Object.defineProperty(PerfCounter.prototype, "average", {
  10037. /**
  10038. * Returns the average value since the performance counter is running
  10039. */
  10040. get: function () {
  10041. return this._average;
  10042. },
  10043. enumerable: true,
  10044. configurable: true
  10045. });
  10046. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10047. /**
  10048. * Returns the average value of the last second the counter was monitored
  10049. */
  10050. get: function () {
  10051. return this._lastSecAverage;
  10052. },
  10053. enumerable: true,
  10054. configurable: true
  10055. });
  10056. Object.defineProperty(PerfCounter.prototype, "current", {
  10057. /**
  10058. * Returns the current value
  10059. */
  10060. get: function () {
  10061. return this._current;
  10062. },
  10063. enumerable: true,
  10064. configurable: true
  10065. });
  10066. Object.defineProperty(PerfCounter.prototype, "total", {
  10067. get: function () {
  10068. return this._totalAccumulated;
  10069. },
  10070. enumerable: true,
  10071. configurable: true
  10072. });
  10073. Object.defineProperty(PerfCounter.prototype, "count", {
  10074. get: function () {
  10075. return this._totalValueCount;
  10076. },
  10077. enumerable: true,
  10078. configurable: true
  10079. });
  10080. /**
  10081. * Call this method to start monitoring a new frame.
  10082. * 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.
  10083. */
  10084. PerfCounter.prototype.fetchNewFrame = function () {
  10085. this._totalValueCount++;
  10086. this._current = 0;
  10087. this._lastSecValueCount++;
  10088. };
  10089. /**
  10090. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10091. * @param newCount the count value to add to the monitored count
  10092. * @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.
  10093. */
  10094. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10095. if (!PerfCounter.Enabled) {
  10096. return;
  10097. }
  10098. this._current += newCount;
  10099. if (fetchResult) {
  10100. this._fetchResult();
  10101. }
  10102. };
  10103. /**
  10104. * Start monitoring this performance counter
  10105. */
  10106. PerfCounter.prototype.beginMonitoring = function () {
  10107. if (!PerfCounter.Enabled) {
  10108. return;
  10109. }
  10110. this._startMonitoringTime = Tools.Now;
  10111. };
  10112. /**
  10113. * Compute the time lapsed since the previous beginMonitoring() call.
  10114. * @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
  10115. */
  10116. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10117. if (newFrame === void 0) { newFrame = true; }
  10118. if (!PerfCounter.Enabled) {
  10119. return;
  10120. }
  10121. if (newFrame) {
  10122. this.fetchNewFrame();
  10123. }
  10124. var currentTime = Tools.Now;
  10125. this._current = currentTime - this._startMonitoringTime;
  10126. if (newFrame) {
  10127. this._fetchResult();
  10128. }
  10129. };
  10130. PerfCounter.prototype._fetchResult = function () {
  10131. this._totalAccumulated += this._current;
  10132. this._lastSecAccumulated += this._current;
  10133. // Min/Max update
  10134. this._min = Math.min(this._min, this._current);
  10135. this._max = Math.max(this._max, this._current);
  10136. this._average = this._totalAccumulated / this._totalValueCount;
  10137. // Reset last sec?
  10138. var now = Tools.Now;
  10139. if ((now - this._lastSecTime) > 1000) {
  10140. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10141. this._lastSecTime = now;
  10142. this._lastSecAccumulated = 0;
  10143. this._lastSecValueCount = 0;
  10144. }
  10145. };
  10146. PerfCounter.Enabled = true;
  10147. return PerfCounter;
  10148. }());
  10149. BABYLON.PerfCounter = PerfCounter;
  10150. /**
  10151. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10152. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10153. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10154. * @param name The name of the class, case should be preserved
  10155. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10156. */
  10157. function className(name, module) {
  10158. return function (target) {
  10159. target["__bjsclassName__"] = name;
  10160. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10161. };
  10162. }
  10163. BABYLON.className = className;
  10164. /**
  10165. * An implementation of a loop for asynchronous functions.
  10166. */
  10167. var AsyncLoop = /** @class */ (function () {
  10168. /**
  10169. * Constroctor.
  10170. * @param iterations the number of iterations.
  10171. * @param _fn the function to run each iteration
  10172. * @param _successCallback the callback that will be called upon succesful execution
  10173. * @param offset starting offset.
  10174. */
  10175. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10176. if (offset === void 0) { offset = 0; }
  10177. this.iterations = iterations;
  10178. this._fn = _fn;
  10179. this._successCallback = _successCallback;
  10180. this.index = offset - 1;
  10181. this._done = false;
  10182. }
  10183. /**
  10184. * Execute the next iteration. Must be called after the last iteration was finished.
  10185. */
  10186. AsyncLoop.prototype.executeNext = function () {
  10187. if (!this._done) {
  10188. if (this.index + 1 < this.iterations) {
  10189. ++this.index;
  10190. this._fn(this);
  10191. }
  10192. else {
  10193. this.breakLoop();
  10194. }
  10195. }
  10196. };
  10197. /**
  10198. * Break the loop and run the success callback.
  10199. */
  10200. AsyncLoop.prototype.breakLoop = function () {
  10201. this._done = true;
  10202. this._successCallback();
  10203. };
  10204. /**
  10205. * Helper function
  10206. */
  10207. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10208. if (offset === void 0) { offset = 0; }
  10209. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10210. loop.executeNext();
  10211. return loop;
  10212. };
  10213. /**
  10214. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10215. * @param iterations total number of iterations
  10216. * @param syncedIterations number of synchronous iterations in each async iteration.
  10217. * @param fn the function to call each iteration.
  10218. * @param callback a success call back that will be called when iterating stops.
  10219. * @param breakFunction a break condition (optional)
  10220. * @param timeout timeout settings for the setTimeout function. default - 0.
  10221. * @constructor
  10222. */
  10223. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10224. if (timeout === void 0) { timeout = 0; }
  10225. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10226. if (breakFunction && breakFunction())
  10227. loop.breakLoop();
  10228. else {
  10229. setTimeout(function () {
  10230. for (var i = 0; i < syncedIterations; ++i) {
  10231. var iteration = (loop.index * syncedIterations) + i;
  10232. if (iteration >= iterations)
  10233. break;
  10234. fn(iteration);
  10235. if (breakFunction && breakFunction()) {
  10236. loop.breakLoop();
  10237. break;
  10238. }
  10239. }
  10240. loop.executeNext();
  10241. }, timeout);
  10242. }
  10243. }, callback);
  10244. };
  10245. return AsyncLoop;
  10246. }());
  10247. BABYLON.AsyncLoop = AsyncLoop;
  10248. })(BABYLON || (BABYLON = {}));
  10249. //# sourceMappingURL=babylon.tools.js.map
  10250. var BABYLON;
  10251. (function (BABYLON) {
  10252. var PromiseStates;
  10253. (function (PromiseStates) {
  10254. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10255. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10256. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10257. })(PromiseStates || (PromiseStates = {}));
  10258. var FulFillmentAgregator = /** @class */ (function () {
  10259. function FulFillmentAgregator() {
  10260. this.count = 0;
  10261. this.target = 0;
  10262. this.results = [];
  10263. }
  10264. return FulFillmentAgregator;
  10265. }());
  10266. var InternalPromise = /** @class */ (function () {
  10267. function InternalPromise(resolver) {
  10268. var _this = this;
  10269. this._state = PromiseStates.Pending;
  10270. this._children = new Array();
  10271. this._rejectWasConsumed = false;
  10272. if (!resolver) {
  10273. return;
  10274. }
  10275. try {
  10276. resolver(function (value) {
  10277. _this._resolve(value);
  10278. }, function (reason) {
  10279. _this._reject(reason);
  10280. });
  10281. }
  10282. catch (e) {
  10283. this._reject(e);
  10284. }
  10285. }
  10286. Object.defineProperty(InternalPromise.prototype, "_result", {
  10287. get: function () {
  10288. return this._resultValue;
  10289. },
  10290. set: function (value) {
  10291. this._resultValue = value;
  10292. if (this._parent && this._parent._result === undefined) {
  10293. this._parent._result = value;
  10294. }
  10295. },
  10296. enumerable: true,
  10297. configurable: true
  10298. });
  10299. InternalPromise.prototype.catch = function (onRejected) {
  10300. return this.then(undefined, onRejected);
  10301. };
  10302. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10303. var _this = this;
  10304. var newPromise = new InternalPromise();
  10305. newPromise._onFulfilled = onFulfilled;
  10306. newPromise._onRejected = onRejected;
  10307. // Composition
  10308. this._children.push(newPromise);
  10309. newPromise._parent = this;
  10310. if (this._state !== PromiseStates.Pending) {
  10311. BABYLON.Tools.SetImmediate(function () {
  10312. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10313. var returnedValue = newPromise._resolve(_this._result);
  10314. if (returnedValue !== undefined && returnedValue !== null) {
  10315. if (returnedValue._state !== undefined) {
  10316. var returnedPromise = returnedValue;
  10317. newPromise._children.push(returnedPromise);
  10318. returnedPromise._parent = newPromise;
  10319. newPromise = returnedPromise;
  10320. }
  10321. else {
  10322. newPromise._result = returnedValue;
  10323. }
  10324. }
  10325. }
  10326. else {
  10327. newPromise._reject(_this._reason);
  10328. }
  10329. });
  10330. }
  10331. return newPromise;
  10332. };
  10333. InternalPromise.prototype._moveChildren = function (children) {
  10334. var _this = this;
  10335. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10336. this._children.forEach(function (child) {
  10337. child._parent = _this;
  10338. });
  10339. if (this._state === PromiseStates.Fulfilled) {
  10340. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10341. var child = _b[_i];
  10342. child._resolve(this._result);
  10343. }
  10344. }
  10345. else if (this._state === PromiseStates.Rejected) {
  10346. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10347. var child = _d[_c];
  10348. child._reject(this._reason);
  10349. }
  10350. }
  10351. var _a;
  10352. };
  10353. InternalPromise.prototype._resolve = function (value) {
  10354. try {
  10355. this._state = PromiseStates.Fulfilled;
  10356. var returnedValue = null;
  10357. if (this._onFulfilled) {
  10358. returnedValue = this._onFulfilled(value);
  10359. }
  10360. if (returnedValue !== undefined && returnedValue !== null) {
  10361. if (returnedValue._state !== undefined) {
  10362. // Transmit children
  10363. var returnedPromise = returnedValue;
  10364. returnedPromise._parent = this;
  10365. returnedPromise._moveChildren(this._children);
  10366. value = returnedPromise._result;
  10367. }
  10368. else {
  10369. value = returnedValue;
  10370. }
  10371. }
  10372. this._result = value;
  10373. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10374. var child = _a[_i];
  10375. child._resolve(value);
  10376. }
  10377. this._children.length = 0;
  10378. delete this._onFulfilled;
  10379. delete this._onRejected;
  10380. }
  10381. catch (e) {
  10382. this._reject(e, true);
  10383. }
  10384. };
  10385. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10386. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10387. this._state = PromiseStates.Rejected;
  10388. this._reason = reason;
  10389. if (this._onRejected && !onLocalThrow) {
  10390. try {
  10391. this._onRejected(reason);
  10392. this._rejectWasConsumed = true;
  10393. }
  10394. catch (e) {
  10395. reason = e;
  10396. }
  10397. }
  10398. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10399. var child = _a[_i];
  10400. if (this._rejectWasConsumed) {
  10401. child._resolve(null);
  10402. }
  10403. else {
  10404. child._reject(reason);
  10405. }
  10406. }
  10407. this._children.length = 0;
  10408. delete this._onFulfilled;
  10409. delete this._onRejected;
  10410. };
  10411. InternalPromise.resolve = function (value) {
  10412. var newPromise = new InternalPromise();
  10413. newPromise._resolve(value);
  10414. return newPromise;
  10415. };
  10416. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10417. promise.then(function (value) {
  10418. agregator.results[index] = value;
  10419. agregator.count++;
  10420. if (agregator.count === agregator.target) {
  10421. agregator.rootPromise._resolve(agregator.results);
  10422. }
  10423. return null;
  10424. }, function (reason) {
  10425. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10426. agregator.rootPromise._reject(reason);
  10427. }
  10428. });
  10429. };
  10430. InternalPromise.all = function (promises) {
  10431. var newPromise = new InternalPromise();
  10432. var agregator = new FulFillmentAgregator();
  10433. agregator.target = promises.length;
  10434. agregator.rootPromise = newPromise;
  10435. if (promises.length) {
  10436. for (var index = 0; index < promises.length; index++) {
  10437. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10438. }
  10439. }
  10440. else {
  10441. newPromise._resolve([]);
  10442. }
  10443. return newPromise;
  10444. };
  10445. InternalPromise.race = function (promises) {
  10446. var newPromise = new InternalPromise();
  10447. if (promises.length) {
  10448. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10449. var promise = promises_1[_i];
  10450. promise.then(function (value) {
  10451. if (newPromise) {
  10452. newPromise._resolve(value);
  10453. newPromise = null;
  10454. }
  10455. return null;
  10456. }, function (reason) {
  10457. if (newPromise) {
  10458. newPromise._reject(reason);
  10459. newPromise = null;
  10460. }
  10461. });
  10462. }
  10463. }
  10464. return newPromise;
  10465. };
  10466. return InternalPromise;
  10467. }());
  10468. /**
  10469. * Helper class that provides a small promise polyfill
  10470. */
  10471. var PromisePolyfill = /** @class */ (function () {
  10472. function PromisePolyfill() {
  10473. }
  10474. /**
  10475. * Static function used to check if the polyfill is required
  10476. * If this is the case then the function will inject the polyfill to window.Promise
  10477. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10478. */
  10479. PromisePolyfill.Apply = function (force) {
  10480. if (force === void 0) { force = false; }
  10481. if (force || typeof Promise === 'undefined') {
  10482. var root = window;
  10483. root.Promise = InternalPromise;
  10484. }
  10485. };
  10486. return PromisePolyfill;
  10487. }());
  10488. BABYLON.PromisePolyfill = PromisePolyfill;
  10489. })(BABYLON || (BABYLON = {}));
  10490. //# sourceMappingURL=babylon.promise.js.map
  10491. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10492. var BABYLON;
  10493. (function (BABYLON) {
  10494. /**
  10495. * Helper class to push actions to a pool of workers.
  10496. */
  10497. var WorkerPool = /** @class */ (function () {
  10498. /**
  10499. * Constructor
  10500. * @param workers Array of workers to use for actions
  10501. */
  10502. function WorkerPool(workers) {
  10503. this._pendingActions = new Array();
  10504. this._workerInfos = workers.map(function (worker) { return ({
  10505. worker: worker,
  10506. active: false
  10507. }); });
  10508. }
  10509. /**
  10510. * Terminates all workers and clears any pending actions.
  10511. */
  10512. WorkerPool.prototype.dispose = function () {
  10513. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10514. var workerInfo = _a[_i];
  10515. workerInfo.worker.terminate();
  10516. }
  10517. delete this._workerInfos;
  10518. delete this._pendingActions;
  10519. };
  10520. /**
  10521. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10522. * pended until a worker has completed its action.
  10523. * @param action The action to perform. Call onComplete when the action is complete.
  10524. */
  10525. WorkerPool.prototype.push = function (action) {
  10526. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10527. var workerInfo = _a[_i];
  10528. if (!workerInfo.active) {
  10529. this._execute(workerInfo, action);
  10530. return;
  10531. }
  10532. }
  10533. this._pendingActions.push(action);
  10534. };
  10535. WorkerPool.prototype._execute = function (workerInfo, action) {
  10536. var _this = this;
  10537. workerInfo.active = true;
  10538. action(workerInfo.worker, function () {
  10539. workerInfo.active = false;
  10540. var nextAction = _this._pendingActions.shift();
  10541. if (nextAction) {
  10542. _this._execute(workerInfo, nextAction);
  10543. }
  10544. });
  10545. };
  10546. return WorkerPool;
  10547. }());
  10548. BABYLON.WorkerPool = WorkerPool;
  10549. })(BABYLON || (BABYLON = {}));
  10550. //# sourceMappingURL=babylon.workerPool.js.map
  10551. var BABYLON;
  10552. (function (BABYLON) {
  10553. /**
  10554. * @hidden
  10555. **/
  10556. var _AlphaState = /** @class */ (function () {
  10557. /**
  10558. * Initializes the state.
  10559. */
  10560. function _AlphaState() {
  10561. this._isAlphaBlendDirty = false;
  10562. this._isBlendFunctionParametersDirty = false;
  10563. this._isBlendEquationParametersDirty = false;
  10564. this._isBlendConstantsDirty = false;
  10565. this._alphaBlend = false;
  10566. this._blendFunctionParameters = new Array(4);
  10567. this._blendEquationParameters = new Array(2);
  10568. this._blendConstants = new Array(4);
  10569. this.reset();
  10570. }
  10571. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10572. get: function () {
  10573. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10574. },
  10575. enumerable: true,
  10576. configurable: true
  10577. });
  10578. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10579. get: function () {
  10580. return this._alphaBlend;
  10581. },
  10582. set: function (value) {
  10583. if (this._alphaBlend === value) {
  10584. return;
  10585. }
  10586. this._alphaBlend = value;
  10587. this._isAlphaBlendDirty = true;
  10588. },
  10589. enumerable: true,
  10590. configurable: true
  10591. });
  10592. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10593. if (this._blendConstants[0] === r &&
  10594. this._blendConstants[1] === g &&
  10595. this._blendConstants[2] === b &&
  10596. this._blendConstants[3] === a) {
  10597. return;
  10598. }
  10599. this._blendConstants[0] = r;
  10600. this._blendConstants[1] = g;
  10601. this._blendConstants[2] = b;
  10602. this._blendConstants[3] = a;
  10603. this._isBlendConstantsDirty = true;
  10604. };
  10605. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10606. if (this._blendFunctionParameters[0] === value0 &&
  10607. this._blendFunctionParameters[1] === value1 &&
  10608. this._blendFunctionParameters[2] === value2 &&
  10609. this._blendFunctionParameters[3] === value3) {
  10610. return;
  10611. }
  10612. this._blendFunctionParameters[0] = value0;
  10613. this._blendFunctionParameters[1] = value1;
  10614. this._blendFunctionParameters[2] = value2;
  10615. this._blendFunctionParameters[3] = value3;
  10616. this._isBlendFunctionParametersDirty = true;
  10617. };
  10618. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10619. if (this._blendEquationParameters[0] === rgb &&
  10620. this._blendEquationParameters[1] === alpha) {
  10621. return;
  10622. }
  10623. this._blendEquationParameters[0] = rgb;
  10624. this._blendEquationParameters[1] = alpha;
  10625. this._isBlendEquationParametersDirty = true;
  10626. };
  10627. _AlphaState.prototype.reset = function () {
  10628. this._alphaBlend = false;
  10629. this._blendFunctionParameters[0] = null;
  10630. this._blendFunctionParameters[1] = null;
  10631. this._blendFunctionParameters[2] = null;
  10632. this._blendFunctionParameters[3] = null;
  10633. this._blendEquationParameters[0] = null;
  10634. this._blendEquationParameters[1] = null;
  10635. this._blendConstants[0] = null;
  10636. this._blendConstants[1] = null;
  10637. this._blendConstants[2] = null;
  10638. this._blendConstants[3] = null;
  10639. this._isAlphaBlendDirty = true;
  10640. this._isBlendFunctionParametersDirty = false;
  10641. this._isBlendEquationParametersDirty = false;
  10642. this._isBlendConstantsDirty = false;
  10643. };
  10644. _AlphaState.prototype.apply = function (gl) {
  10645. if (!this.isDirty) {
  10646. return;
  10647. }
  10648. // Alpha blend
  10649. if (this._isAlphaBlendDirty) {
  10650. if (this._alphaBlend) {
  10651. gl.enable(gl.BLEND);
  10652. }
  10653. else {
  10654. gl.disable(gl.BLEND);
  10655. }
  10656. this._isAlphaBlendDirty = false;
  10657. }
  10658. // Alpha function
  10659. if (this._isBlendFunctionParametersDirty) {
  10660. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10661. this._isBlendFunctionParametersDirty = false;
  10662. }
  10663. // Alpha equation
  10664. if (this._isBlendEquationParametersDirty) {
  10665. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10666. this._isBlendEquationParametersDirty = false;
  10667. }
  10668. // Constants
  10669. if (this._isBlendConstantsDirty) {
  10670. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10671. this._isBlendConstantsDirty = false;
  10672. }
  10673. };
  10674. return _AlphaState;
  10675. }());
  10676. BABYLON._AlphaState = _AlphaState;
  10677. })(BABYLON || (BABYLON = {}));
  10678. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10679. var BABYLON;
  10680. (function (BABYLON) {
  10681. /**
  10682. * @hidden
  10683. **/
  10684. var _DepthCullingState = /** @class */ (function () {
  10685. /**
  10686. * Initializes the state.
  10687. */
  10688. function _DepthCullingState() {
  10689. this._isDepthTestDirty = false;
  10690. this._isDepthMaskDirty = false;
  10691. this._isDepthFuncDirty = false;
  10692. this._isCullFaceDirty = false;
  10693. this._isCullDirty = false;
  10694. this._isZOffsetDirty = false;
  10695. this._isFrontFaceDirty = false;
  10696. this.reset();
  10697. }
  10698. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10699. get: function () {
  10700. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10701. },
  10702. enumerable: true,
  10703. configurable: true
  10704. });
  10705. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10706. get: function () {
  10707. return this._zOffset;
  10708. },
  10709. set: function (value) {
  10710. if (this._zOffset === value) {
  10711. return;
  10712. }
  10713. this._zOffset = value;
  10714. this._isZOffsetDirty = true;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10720. get: function () {
  10721. return this._cullFace;
  10722. },
  10723. set: function (value) {
  10724. if (this._cullFace === value) {
  10725. return;
  10726. }
  10727. this._cullFace = value;
  10728. this._isCullFaceDirty = true;
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10734. get: function () {
  10735. return this._cull;
  10736. },
  10737. set: function (value) {
  10738. if (this._cull === value) {
  10739. return;
  10740. }
  10741. this._cull = value;
  10742. this._isCullDirty = true;
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10748. get: function () {
  10749. return this._depthFunc;
  10750. },
  10751. set: function (value) {
  10752. if (this._depthFunc === value) {
  10753. return;
  10754. }
  10755. this._depthFunc = value;
  10756. this._isDepthFuncDirty = true;
  10757. },
  10758. enumerable: true,
  10759. configurable: true
  10760. });
  10761. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10762. get: function () {
  10763. return this._depthMask;
  10764. },
  10765. set: function (value) {
  10766. if (this._depthMask === value) {
  10767. return;
  10768. }
  10769. this._depthMask = value;
  10770. this._isDepthMaskDirty = true;
  10771. },
  10772. enumerable: true,
  10773. configurable: true
  10774. });
  10775. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10776. get: function () {
  10777. return this._depthTest;
  10778. },
  10779. set: function (value) {
  10780. if (this._depthTest === value) {
  10781. return;
  10782. }
  10783. this._depthTest = value;
  10784. this._isDepthTestDirty = true;
  10785. },
  10786. enumerable: true,
  10787. configurable: true
  10788. });
  10789. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10790. get: function () {
  10791. return this._frontFace;
  10792. },
  10793. set: function (value) {
  10794. if (this._frontFace === value) {
  10795. return;
  10796. }
  10797. this._frontFace = value;
  10798. this._isFrontFaceDirty = true;
  10799. },
  10800. enumerable: true,
  10801. configurable: true
  10802. });
  10803. _DepthCullingState.prototype.reset = function () {
  10804. this._depthMask = true;
  10805. this._depthTest = true;
  10806. this._depthFunc = null;
  10807. this._cullFace = null;
  10808. this._cull = null;
  10809. this._zOffset = 0;
  10810. this._frontFace = null;
  10811. this._isDepthTestDirty = true;
  10812. this._isDepthMaskDirty = true;
  10813. this._isDepthFuncDirty = false;
  10814. this._isCullFaceDirty = false;
  10815. this._isCullDirty = false;
  10816. this._isZOffsetDirty = false;
  10817. this._isFrontFaceDirty = false;
  10818. };
  10819. _DepthCullingState.prototype.apply = function (gl) {
  10820. if (!this.isDirty) {
  10821. return;
  10822. }
  10823. // Cull
  10824. if (this._isCullDirty) {
  10825. if (this.cull) {
  10826. gl.enable(gl.CULL_FACE);
  10827. }
  10828. else {
  10829. gl.disable(gl.CULL_FACE);
  10830. }
  10831. this._isCullDirty = false;
  10832. }
  10833. // Cull face
  10834. if (this._isCullFaceDirty) {
  10835. gl.cullFace(this.cullFace);
  10836. this._isCullFaceDirty = false;
  10837. }
  10838. // Depth mask
  10839. if (this._isDepthMaskDirty) {
  10840. gl.depthMask(this.depthMask);
  10841. this._isDepthMaskDirty = false;
  10842. }
  10843. // Depth test
  10844. if (this._isDepthTestDirty) {
  10845. if (this.depthTest) {
  10846. gl.enable(gl.DEPTH_TEST);
  10847. }
  10848. else {
  10849. gl.disable(gl.DEPTH_TEST);
  10850. }
  10851. this._isDepthTestDirty = false;
  10852. }
  10853. // Depth func
  10854. if (this._isDepthFuncDirty) {
  10855. gl.depthFunc(this.depthFunc);
  10856. this._isDepthFuncDirty = false;
  10857. }
  10858. // zOffset
  10859. if (this._isZOffsetDirty) {
  10860. if (this.zOffset) {
  10861. gl.enable(gl.POLYGON_OFFSET_FILL);
  10862. gl.polygonOffset(this.zOffset, 0);
  10863. }
  10864. else {
  10865. gl.disable(gl.POLYGON_OFFSET_FILL);
  10866. }
  10867. this._isZOffsetDirty = false;
  10868. }
  10869. // Front face
  10870. if (this._isFrontFaceDirty) {
  10871. gl.frontFace(this.frontFace);
  10872. this._isFrontFaceDirty = false;
  10873. }
  10874. };
  10875. return _DepthCullingState;
  10876. }());
  10877. BABYLON._DepthCullingState = _DepthCullingState;
  10878. })(BABYLON || (BABYLON = {}));
  10879. //# sourceMappingURL=babylon.depthCullingState.js.map
  10880. var BABYLON;
  10881. (function (BABYLON) {
  10882. /**
  10883. * @hidden
  10884. **/
  10885. var _StencilState = /** @class */ (function () {
  10886. function _StencilState() {
  10887. this._isStencilTestDirty = false;
  10888. this._isStencilMaskDirty = false;
  10889. this._isStencilFuncDirty = false;
  10890. this._isStencilOpDirty = false;
  10891. this.reset();
  10892. }
  10893. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10894. get: function () {
  10895. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10896. },
  10897. enumerable: true,
  10898. configurable: true
  10899. });
  10900. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10901. get: function () {
  10902. return this._stencilFunc;
  10903. },
  10904. set: function (value) {
  10905. if (this._stencilFunc === value) {
  10906. return;
  10907. }
  10908. this._stencilFunc = value;
  10909. this._isStencilFuncDirty = true;
  10910. },
  10911. enumerable: true,
  10912. configurable: true
  10913. });
  10914. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10915. get: function () {
  10916. return this._stencilFuncRef;
  10917. },
  10918. set: function (value) {
  10919. if (this._stencilFuncRef === value) {
  10920. return;
  10921. }
  10922. this._stencilFuncRef = value;
  10923. this._isStencilFuncDirty = true;
  10924. },
  10925. enumerable: true,
  10926. configurable: true
  10927. });
  10928. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10929. get: function () {
  10930. return this._stencilFuncMask;
  10931. },
  10932. set: function (value) {
  10933. if (this._stencilFuncMask === value) {
  10934. return;
  10935. }
  10936. this._stencilFuncMask = value;
  10937. this._isStencilFuncDirty = true;
  10938. },
  10939. enumerable: true,
  10940. configurable: true
  10941. });
  10942. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10943. get: function () {
  10944. return this._stencilOpStencilFail;
  10945. },
  10946. set: function (value) {
  10947. if (this._stencilOpStencilFail === value) {
  10948. return;
  10949. }
  10950. this._stencilOpStencilFail = value;
  10951. this._isStencilOpDirty = true;
  10952. },
  10953. enumerable: true,
  10954. configurable: true
  10955. });
  10956. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10957. get: function () {
  10958. return this._stencilOpDepthFail;
  10959. },
  10960. set: function (value) {
  10961. if (this._stencilOpDepthFail === value) {
  10962. return;
  10963. }
  10964. this._stencilOpDepthFail = value;
  10965. this._isStencilOpDirty = true;
  10966. },
  10967. enumerable: true,
  10968. configurable: true
  10969. });
  10970. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10971. get: function () {
  10972. return this._stencilOpStencilDepthPass;
  10973. },
  10974. set: function (value) {
  10975. if (this._stencilOpStencilDepthPass === value) {
  10976. return;
  10977. }
  10978. this._stencilOpStencilDepthPass = value;
  10979. this._isStencilOpDirty = true;
  10980. },
  10981. enumerable: true,
  10982. configurable: true
  10983. });
  10984. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10985. get: function () {
  10986. return this._stencilMask;
  10987. },
  10988. set: function (value) {
  10989. if (this._stencilMask === value) {
  10990. return;
  10991. }
  10992. this._stencilMask = value;
  10993. this._isStencilMaskDirty = true;
  10994. },
  10995. enumerable: true,
  10996. configurable: true
  10997. });
  10998. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10999. get: function () {
  11000. return this._stencilTest;
  11001. },
  11002. set: function (value) {
  11003. if (this._stencilTest === value) {
  11004. return;
  11005. }
  11006. this._stencilTest = value;
  11007. this._isStencilTestDirty = true;
  11008. },
  11009. enumerable: true,
  11010. configurable: true
  11011. });
  11012. _StencilState.prototype.reset = function () {
  11013. this._stencilTest = false;
  11014. this._stencilMask = 0xFF;
  11015. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11016. this._stencilFuncRef = 1;
  11017. this._stencilFuncMask = 0xFF;
  11018. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11019. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11020. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11021. this._isStencilTestDirty = true;
  11022. this._isStencilMaskDirty = true;
  11023. this._isStencilFuncDirty = true;
  11024. this._isStencilOpDirty = true;
  11025. };
  11026. _StencilState.prototype.apply = function (gl) {
  11027. if (!this.isDirty) {
  11028. return;
  11029. }
  11030. // Stencil test
  11031. if (this._isStencilTestDirty) {
  11032. if (this.stencilTest) {
  11033. gl.enable(gl.STENCIL_TEST);
  11034. }
  11035. else {
  11036. gl.disable(gl.STENCIL_TEST);
  11037. }
  11038. this._isStencilTestDirty = false;
  11039. }
  11040. // Stencil mask
  11041. if (this._isStencilMaskDirty) {
  11042. gl.stencilMask(this.stencilMask);
  11043. this._isStencilMaskDirty = false;
  11044. }
  11045. // Stencil func
  11046. if (this._isStencilFuncDirty) {
  11047. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11048. this._isStencilFuncDirty = false;
  11049. }
  11050. // Stencil op
  11051. if (this._isStencilOpDirty) {
  11052. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11053. this._isStencilOpDirty = false;
  11054. }
  11055. };
  11056. return _StencilState;
  11057. }());
  11058. BABYLON._StencilState = _StencilState;
  11059. })(BABYLON || (BABYLON = {}));
  11060. //# sourceMappingURL=babylon.stencilState.js.map
  11061. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11062. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11063. s = arguments[i];
  11064. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11065. t[p] = s[p];
  11066. }
  11067. return t;
  11068. };
  11069. var BABYLON;
  11070. (function (BABYLON) {
  11071. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11072. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11073. };
  11074. var compileRawShader = function (gl, source, type) {
  11075. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11076. gl.shaderSource(shader, source);
  11077. gl.compileShader(shader);
  11078. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11079. var log = gl.getShaderInfoLog(shader);
  11080. if (log) {
  11081. throw new Error(log);
  11082. }
  11083. }
  11084. if (!shader) {
  11085. throw new Error("Something went wrong while compile the shader.");
  11086. }
  11087. return shader;
  11088. };
  11089. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11090. var magFilter = gl.NEAREST;
  11091. var minFilter = gl.NEAREST;
  11092. switch (samplingMode) {
  11093. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11094. magFilter = gl.LINEAR;
  11095. if (generateMipMaps) {
  11096. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11097. }
  11098. else {
  11099. minFilter = gl.LINEAR;
  11100. }
  11101. break;
  11102. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11103. magFilter = gl.LINEAR;
  11104. if (generateMipMaps) {
  11105. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11106. }
  11107. else {
  11108. minFilter = gl.LINEAR;
  11109. }
  11110. break;
  11111. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11112. magFilter = gl.NEAREST;
  11113. if (generateMipMaps) {
  11114. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11115. }
  11116. else {
  11117. minFilter = gl.NEAREST;
  11118. }
  11119. break;
  11120. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11121. magFilter = gl.NEAREST;
  11122. if (generateMipMaps) {
  11123. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11124. }
  11125. else {
  11126. minFilter = gl.NEAREST;
  11127. }
  11128. break;
  11129. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11130. magFilter = gl.NEAREST;
  11131. if (generateMipMaps) {
  11132. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11133. }
  11134. else {
  11135. minFilter = gl.LINEAR;
  11136. }
  11137. break;
  11138. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11139. magFilter = gl.NEAREST;
  11140. if (generateMipMaps) {
  11141. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11142. }
  11143. else {
  11144. minFilter = gl.LINEAR;
  11145. }
  11146. break;
  11147. case BABYLON.Texture.NEAREST_LINEAR:
  11148. magFilter = gl.NEAREST;
  11149. minFilter = gl.LINEAR;
  11150. break;
  11151. case BABYLON.Texture.NEAREST_NEAREST:
  11152. magFilter = gl.NEAREST;
  11153. minFilter = gl.NEAREST;
  11154. break;
  11155. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11156. magFilter = gl.LINEAR;
  11157. if (generateMipMaps) {
  11158. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11159. }
  11160. else {
  11161. minFilter = gl.NEAREST;
  11162. }
  11163. break;
  11164. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11165. magFilter = gl.LINEAR;
  11166. if (generateMipMaps) {
  11167. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11168. }
  11169. else {
  11170. minFilter = gl.NEAREST;
  11171. }
  11172. break;
  11173. case BABYLON.Texture.LINEAR_LINEAR:
  11174. magFilter = gl.LINEAR;
  11175. minFilter = gl.LINEAR;
  11176. break;
  11177. case BABYLON.Texture.LINEAR_NEAREST:
  11178. magFilter = gl.LINEAR;
  11179. minFilter = gl.NEAREST;
  11180. break;
  11181. }
  11182. return {
  11183. min: minFilter,
  11184. mag: magFilter
  11185. };
  11186. };
  11187. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11188. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11189. var img;
  11190. var onload = function () {
  11191. loadedImages[index] = img;
  11192. loadedImages._internalCount++;
  11193. if (scene) {
  11194. scene._removePendingData(img);
  11195. }
  11196. if (loadedImages._internalCount === 6) {
  11197. onfinish(loadedImages);
  11198. }
  11199. };
  11200. var onerror = function (message, exception) {
  11201. if (scene) {
  11202. scene._removePendingData(img);
  11203. }
  11204. if (onErrorCallBack) {
  11205. onErrorCallBack(message, exception);
  11206. }
  11207. };
  11208. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11209. if (scene) {
  11210. scene._addPendingData(img);
  11211. }
  11212. };
  11213. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11214. if (onError === void 0) { onError = null; }
  11215. var loadedImages = [];
  11216. loadedImages._internalCount = 0;
  11217. for (var index = 0; index < 6; index++) {
  11218. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11219. }
  11220. };
  11221. var BufferPointer = /** @class */ (function () {
  11222. function BufferPointer() {
  11223. }
  11224. return BufferPointer;
  11225. }());
  11226. /**
  11227. * Interface for attribute information associated with buffer instanciation
  11228. */
  11229. var InstancingAttributeInfo = /** @class */ (function () {
  11230. function InstancingAttributeInfo() {
  11231. }
  11232. return InstancingAttributeInfo;
  11233. }());
  11234. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11235. /**
  11236. * Define options used to create a render target texture
  11237. */
  11238. var RenderTargetCreationOptions = /** @class */ (function () {
  11239. function RenderTargetCreationOptions() {
  11240. }
  11241. return RenderTargetCreationOptions;
  11242. }());
  11243. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11244. /**
  11245. * Define options used to create a depth texture
  11246. */
  11247. var DepthTextureCreationOptions = /** @class */ (function () {
  11248. function DepthTextureCreationOptions() {
  11249. }
  11250. return DepthTextureCreationOptions;
  11251. }());
  11252. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11253. /**
  11254. * Class used to describe the capabilities of the engine relatively to the current browser
  11255. */
  11256. var EngineCapabilities = /** @class */ (function () {
  11257. function EngineCapabilities() {
  11258. }
  11259. return EngineCapabilities;
  11260. }());
  11261. BABYLON.EngineCapabilities = EngineCapabilities;
  11262. /**
  11263. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11264. */
  11265. var Engine = /** @class */ (function () {
  11266. /**
  11267. * Creates a new engine
  11268. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11269. * @param antialias defines enable antialiasing (default: false)
  11270. * @param options defines further options to be sent to the getContext() function
  11271. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11272. */
  11273. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11274. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11275. var _this = this;
  11276. // Public members
  11277. /**
  11278. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11279. */
  11280. this.forcePOTTextures = false;
  11281. /**
  11282. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11283. */
  11284. this.isFullscreen = false;
  11285. /**
  11286. * Gets a boolean indicating if the pointer is currently locked
  11287. */
  11288. this.isPointerLock = false;
  11289. /**
  11290. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11291. */
  11292. this.cullBackFaces = true;
  11293. /**
  11294. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11295. */
  11296. this.renderEvenInBackground = true;
  11297. /**
  11298. * Gets or sets a boolean indicating that cache can be kept between frames
  11299. */
  11300. this.preventCacheWipeBetweenFrames = false;
  11301. /**
  11302. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11303. **/
  11304. this.enableOfflineSupport = false;
  11305. /**
  11306. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11307. **/
  11308. this.disableManifestCheck = false;
  11309. /**
  11310. * Gets the list of created scenes
  11311. */
  11312. this.scenes = new Array();
  11313. /**
  11314. * Gets the list of created postprocesses
  11315. */
  11316. this.postProcesses = new Array();
  11317. // Observables
  11318. /**
  11319. * Observable event triggered each time the rendering canvas is resized
  11320. */
  11321. this.onResizeObservable = new BABYLON.Observable();
  11322. /**
  11323. * Observable event triggered each time the canvas loses focus
  11324. */
  11325. this.onCanvasBlurObservable = new BABYLON.Observable();
  11326. /**
  11327. * Observable event triggered each time the canvas gains focus
  11328. */
  11329. this.onCanvasFocusObservable = new BABYLON.Observable();
  11330. /**
  11331. * Observable event triggered each time the canvas receives pointerout event
  11332. */
  11333. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11334. /**
  11335. * Observable event triggered before each texture is initialized
  11336. */
  11337. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11338. //WebVR
  11339. this._vrDisplay = undefined;
  11340. this._vrSupported = false;
  11341. this._vrExclusivePointerMode = false;
  11342. // Uniform buffers list
  11343. /**
  11344. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11345. */
  11346. this.disableUniformBuffers = false;
  11347. /** @hidden */
  11348. this._uniformBuffers = new Array();
  11349. // Observables
  11350. /**
  11351. * Observable raised when the engine begins a new frame
  11352. */
  11353. this.onBeginFrameObservable = new BABYLON.Observable();
  11354. /**
  11355. * Observable raised when the engine ends the current frame
  11356. */
  11357. this.onEndFrameObservable = new BABYLON.Observable();
  11358. /**
  11359. * Observable raised when the engine is about to compile a shader
  11360. */
  11361. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11362. /**
  11363. * Observable raised when the engine has jsut compiled a shader
  11364. */
  11365. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11366. this._windowIsBackground = false;
  11367. this._webGLVersion = 1.0;
  11368. /** @hidden */
  11369. this._badOS = false;
  11370. /** @hidden */
  11371. this._badDesktopOS = false;
  11372. /**
  11373. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11374. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11375. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11376. */
  11377. this.disableTextureBindingOptimization = false;
  11378. /**
  11379. * Observable signaled when VR display mode changes
  11380. */
  11381. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11382. /**
  11383. * Observable signaled when VR request present is complete
  11384. */
  11385. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11386. /**
  11387. * Observable signaled when VR request present starts
  11388. */
  11389. this.onVRRequestPresentStart = new BABYLON.Observable();
  11390. this._colorWrite = true;
  11391. /** @hidden */
  11392. this._drawCalls = new BABYLON.PerfCounter();
  11393. /** @hidden */
  11394. this._textureCollisions = new BABYLON.PerfCounter();
  11395. this._renderingQueueLaunched = false;
  11396. this._activeRenderLoops = new Array();
  11397. // Deterministic lockstepMaxSteps
  11398. this._deterministicLockstep = false;
  11399. this._lockstepMaxSteps = 4;
  11400. // Lost context
  11401. /**
  11402. * Observable signaled when a context lost event is raised
  11403. */
  11404. this.onContextLostObservable = new BABYLON.Observable();
  11405. /**
  11406. * Observable signaled when a context restored event is raised
  11407. */
  11408. this.onContextRestoredObservable = new BABYLON.Observable();
  11409. this._contextWasLost = false;
  11410. this._doNotHandleContextLost = false;
  11411. // FPS
  11412. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11413. this._fps = 60;
  11414. this._deltaTime = 0;
  11415. /**
  11416. * Turn this value on if you want to pause FPS computation when in background
  11417. */
  11418. this.disablePerformanceMonitorInBackground = false;
  11419. // States
  11420. /** @hidden */
  11421. this._depthCullingState = new BABYLON._DepthCullingState();
  11422. /** @hidden */
  11423. this._stencilState = new BABYLON._StencilState();
  11424. /** @hidden */
  11425. this._alphaState = new BABYLON._AlphaState();
  11426. /** @hidden */
  11427. this._alphaMode = Engine.ALPHA_DISABLE;
  11428. // Cache
  11429. this._internalTexturesCache = new Array();
  11430. /** @hidden */
  11431. this._activeChannel = 0;
  11432. this._currentTextureChannel = -1;
  11433. /** @hidden */
  11434. this._boundTexturesCache = {};
  11435. this._compiledEffects = {};
  11436. this._vertexAttribArraysEnabled = [];
  11437. this._uintIndicesCurrentlySet = false;
  11438. this._currentBoundBuffer = new Array();
  11439. /** @hidden */
  11440. this._currentFramebuffer = null;
  11441. this._currentBufferPointers = new Array();
  11442. this._currentInstanceLocations = new Array();
  11443. this._currentInstanceBuffers = new Array();
  11444. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11445. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11446. this._vaoRecordInProgress = false;
  11447. this._mustWipeVertexAttributes = false;
  11448. this._nextFreeTextureSlots = new Array();
  11449. this._maxSimultaneousTextures = 0;
  11450. this._activeRequests = new Array();
  11451. // Hardware supported Compressed Textures
  11452. this._texturesSupported = new Array();
  11453. /**
  11454. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11455. */
  11456. this.premultipliedAlpha = true;
  11457. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11458. this._onVRFullScreenTriggered = function () {
  11459. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11460. //get the old size before we change
  11461. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11462. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11463. //get the width and height, change the render size
  11464. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11465. _this.setHardwareScalingLevel(1);
  11466. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11467. }
  11468. else {
  11469. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11470. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11471. }
  11472. };
  11473. this._unpackFlipYCached = null;
  11474. this._boundUniforms = {};
  11475. // Register promises
  11476. BABYLON.PromisePolyfill.Apply();
  11477. var canvas = null;
  11478. Engine.Instances.push(this);
  11479. if (!canvasOrContext) {
  11480. return;
  11481. }
  11482. options = options || {};
  11483. if (canvasOrContext.getContext) {
  11484. canvas = canvasOrContext;
  11485. this._renderingCanvas = canvas;
  11486. if (antialias != null) {
  11487. options.antialias = antialias;
  11488. }
  11489. if (options.deterministicLockstep === undefined) {
  11490. options.deterministicLockstep = false;
  11491. }
  11492. if (options.lockstepMaxSteps === undefined) {
  11493. options.lockstepMaxSteps = 4;
  11494. }
  11495. if (options.preserveDrawingBuffer === undefined) {
  11496. options.preserveDrawingBuffer = false;
  11497. }
  11498. if (options.audioEngine === undefined) {
  11499. options.audioEngine = true;
  11500. }
  11501. if (options.stencil === undefined) {
  11502. options.stencil = true;
  11503. }
  11504. if (options.premultipliedAlpha === false) {
  11505. this.premultipliedAlpha = false;
  11506. }
  11507. this._deterministicLockstep = options.deterministicLockstep;
  11508. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11509. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11510. // Exceptions
  11511. if (navigator && navigator.userAgent) {
  11512. var ua = navigator.userAgent;
  11513. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11514. var exception = _a[_i];
  11515. var key = exception.key;
  11516. var targets = exception.targets;
  11517. if (ua.indexOf(key) > -1) {
  11518. if (exception.capture && exception.captureConstraint) {
  11519. var capture = exception.capture;
  11520. var constraint = exception.captureConstraint;
  11521. var regex = new RegExp(capture);
  11522. var matches = regex.exec(ua);
  11523. if (matches && matches.length > 0) {
  11524. var capturedValue = parseInt(matches[matches.length - 1]);
  11525. if (capturedValue >= constraint) {
  11526. continue;
  11527. }
  11528. }
  11529. }
  11530. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11531. var target = targets_1[_b];
  11532. switch (target) {
  11533. case "uniformBuffer":
  11534. this.disableUniformBuffers = true;
  11535. break;
  11536. case "textureBindingOptimization":
  11537. this.disableTextureBindingOptimization = true;
  11538. break;
  11539. }
  11540. }
  11541. }
  11542. }
  11543. }
  11544. // GL
  11545. if (!options.disableWebGL2Support) {
  11546. try {
  11547. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11548. if (this._gl) {
  11549. this._webGLVersion = 2.0;
  11550. }
  11551. }
  11552. catch (e) {
  11553. // Do nothing
  11554. }
  11555. }
  11556. if (!this._gl) {
  11557. if (!canvas) {
  11558. throw new Error("The provided canvas is null or undefined.");
  11559. }
  11560. try {
  11561. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11562. }
  11563. catch (e) {
  11564. throw new Error("WebGL not supported");
  11565. }
  11566. }
  11567. if (!this._gl) {
  11568. throw new Error("WebGL not supported");
  11569. }
  11570. this._onCanvasFocus = function () {
  11571. _this.onCanvasFocusObservable.notifyObservers(_this);
  11572. };
  11573. this._onCanvasBlur = function () {
  11574. _this.onCanvasBlurObservable.notifyObservers(_this);
  11575. };
  11576. canvas.addEventListener("focus", this._onCanvasFocus);
  11577. canvas.addEventListener("blur", this._onCanvasBlur);
  11578. this._onBlur = function () {
  11579. if (_this.disablePerformanceMonitorInBackground) {
  11580. _this._performanceMonitor.disable();
  11581. }
  11582. _this._windowIsBackground = true;
  11583. };
  11584. this._onFocus = function () {
  11585. if (_this.disablePerformanceMonitorInBackground) {
  11586. _this._performanceMonitor.enable();
  11587. }
  11588. _this._windowIsBackground = false;
  11589. };
  11590. this._onCanvasPointerOut = function (ev) {
  11591. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11592. };
  11593. window.addEventListener("blur", this._onBlur);
  11594. window.addEventListener("focus", this._onFocus);
  11595. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11596. // Context lost
  11597. if (!this._doNotHandleContextLost) {
  11598. this._onContextLost = function (evt) {
  11599. evt.preventDefault();
  11600. _this._contextWasLost = true;
  11601. BABYLON.Tools.Warn("WebGL context lost.");
  11602. _this.onContextLostObservable.notifyObservers(_this);
  11603. };
  11604. this._onContextRestored = function (evt) {
  11605. // Adding a timeout to avoid race condition at browser level
  11606. setTimeout(function () {
  11607. // Rebuild gl context
  11608. _this._initGLContext();
  11609. // Rebuild effects
  11610. _this._rebuildEffects();
  11611. // Rebuild textures
  11612. _this._rebuildInternalTextures();
  11613. // Rebuild buffers
  11614. _this._rebuildBuffers();
  11615. // Cache
  11616. _this.wipeCaches(true);
  11617. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11618. _this.onContextRestoredObservable.notifyObservers(_this);
  11619. _this._contextWasLost = false;
  11620. }, 0);
  11621. };
  11622. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11623. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11624. }
  11625. }
  11626. else {
  11627. this._gl = canvasOrContext;
  11628. this._renderingCanvas = this._gl.canvas;
  11629. if (this._gl.renderbufferStorageMultisample) {
  11630. this._webGLVersion = 2.0;
  11631. }
  11632. options.stencil = this._gl.getContextAttributes().stencil;
  11633. }
  11634. // Viewport
  11635. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11636. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11637. this.resize();
  11638. this._isStencilEnable = options.stencil ? true : false;
  11639. this._initGLContext();
  11640. if (canvas) {
  11641. // Fullscreen
  11642. this._onFullscreenChange = function () {
  11643. if (document.fullscreen !== undefined) {
  11644. _this.isFullscreen = document.fullscreen;
  11645. }
  11646. else if (document.mozFullScreen !== undefined) {
  11647. _this.isFullscreen = document.mozFullScreen;
  11648. }
  11649. else if (document.webkitIsFullScreen !== undefined) {
  11650. _this.isFullscreen = document.webkitIsFullScreen;
  11651. }
  11652. else if (document.msIsFullScreen !== undefined) {
  11653. _this.isFullscreen = document.msIsFullScreen;
  11654. }
  11655. // Pointer lock
  11656. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11657. canvas.requestPointerLock = canvas.requestPointerLock ||
  11658. canvas.msRequestPointerLock ||
  11659. canvas.mozRequestPointerLock ||
  11660. canvas.webkitRequestPointerLock;
  11661. if (canvas.requestPointerLock) {
  11662. canvas.requestPointerLock();
  11663. }
  11664. }
  11665. };
  11666. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11667. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11668. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11669. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11670. // Pointer lock
  11671. this._onPointerLockChange = function () {
  11672. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11673. document.webkitPointerLockElement === canvas ||
  11674. document.msPointerLockElement === canvas ||
  11675. document.pointerLockElement === canvas);
  11676. };
  11677. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11678. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11679. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11680. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11681. this._onVRDisplayPointerRestricted = function () {
  11682. if (canvas) {
  11683. canvas.requestPointerLock();
  11684. }
  11685. };
  11686. this._onVRDisplayPointerUnrestricted = function () {
  11687. document.exitPointerLock();
  11688. };
  11689. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11690. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11691. }
  11692. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11693. Engine.audioEngine = new BABYLON.AudioEngine();
  11694. }
  11695. // Prepare buffer pointers
  11696. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11697. this._currentBufferPointers[i] = new BufferPointer();
  11698. }
  11699. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11700. // Load WebVR Devices
  11701. if (options.autoEnableWebVR) {
  11702. this.initWebVR();
  11703. }
  11704. // Detect if we are running on a faulty buggy OS.
  11705. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11706. // Detect if we are running on a faulty buggy desktop OS.
  11707. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11708. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11709. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11710. }
  11711. Object.defineProperty(Engine, "LastCreatedEngine", {
  11712. /**
  11713. * Gets the latest created engine
  11714. */
  11715. get: function () {
  11716. if (Engine.Instances.length === 0) {
  11717. return null;
  11718. }
  11719. return Engine.Instances[Engine.Instances.length - 1];
  11720. },
  11721. enumerable: true,
  11722. configurable: true
  11723. });
  11724. Object.defineProperty(Engine, "LastCreatedScene", {
  11725. /**
  11726. * Gets the latest created scene
  11727. */
  11728. get: function () {
  11729. var lastCreatedEngine = Engine.LastCreatedEngine;
  11730. if (!lastCreatedEngine) {
  11731. return null;
  11732. }
  11733. if (lastCreatedEngine.scenes.length === 0) {
  11734. return null;
  11735. }
  11736. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. /**
  11742. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11743. * @param flag defines which part of the materials must be marked as dirty
  11744. * @param predicate defines a predicate used to filter which materials should be affected
  11745. */
  11746. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11747. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11748. var engine = Engine.Instances[engineIndex];
  11749. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11750. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11751. }
  11752. }
  11753. };
  11754. Object.defineProperty(Engine, "NEVER", {
  11755. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11756. get: function () {
  11757. return Engine._NEVER;
  11758. },
  11759. enumerable: true,
  11760. configurable: true
  11761. });
  11762. Object.defineProperty(Engine, "ALWAYS", {
  11763. /** 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 */
  11764. get: function () {
  11765. return Engine._ALWAYS;
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Object.defineProperty(Engine, "LESS", {
  11771. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11772. get: function () {
  11773. return Engine._LESS;
  11774. },
  11775. enumerable: true,
  11776. configurable: true
  11777. });
  11778. Object.defineProperty(Engine, "EQUAL", {
  11779. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11780. get: function () {
  11781. return Engine._EQUAL;
  11782. },
  11783. enumerable: true,
  11784. configurable: true
  11785. });
  11786. Object.defineProperty(Engine, "LEQUAL", {
  11787. /** 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 */
  11788. get: function () {
  11789. return Engine._LEQUAL;
  11790. },
  11791. enumerable: true,
  11792. configurable: true
  11793. });
  11794. Object.defineProperty(Engine, "GREATER", {
  11795. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11796. get: function () {
  11797. return Engine._GREATER;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(Engine, "GEQUAL", {
  11803. /** 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 */
  11804. get: function () {
  11805. return Engine._GEQUAL;
  11806. },
  11807. enumerable: true,
  11808. configurable: true
  11809. });
  11810. Object.defineProperty(Engine, "NOTEQUAL", {
  11811. /** 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 */
  11812. get: function () {
  11813. return Engine._NOTEQUAL;
  11814. },
  11815. enumerable: true,
  11816. configurable: true
  11817. });
  11818. Object.defineProperty(Engine, "KEEP", {
  11819. /** Passed to stencilOperation to specify that stencil value must be kept */
  11820. get: function () {
  11821. return Engine._KEEP;
  11822. },
  11823. enumerable: true,
  11824. configurable: true
  11825. });
  11826. Object.defineProperty(Engine, "REPLACE", {
  11827. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11828. get: function () {
  11829. return Engine._REPLACE;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine, "INCR", {
  11835. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11836. get: function () {
  11837. return Engine._INCR;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(Engine, "DECR", {
  11843. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11844. get: function () {
  11845. return Engine._DECR;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Engine, "INVERT", {
  11851. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11852. get: function () {
  11853. return Engine._INVERT;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine, "INCR_WRAP", {
  11859. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11860. get: function () {
  11861. return Engine._INCR_WRAP;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(Engine, "DECR_WRAP", {
  11867. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11868. get: function () {
  11869. return Engine._DECR_WRAP;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11875. // Alpha
  11876. /** Defines that alpha blending is disabled */
  11877. get: function () {
  11878. return Engine._ALPHA_DISABLE;
  11879. },
  11880. enumerable: true,
  11881. configurable: true
  11882. });
  11883. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11884. /** Defines that alpha blending to SRC + DEST */
  11885. get: function () {
  11886. return Engine._ALPHA_ONEONE;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(Engine, "ALPHA_ADD", {
  11892. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11893. get: function () {
  11894. return Engine._ALPHA_ADD;
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11900. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11901. get: function () {
  11902. return Engine._ALPHA_COMBINE;
  11903. },
  11904. enumerable: true,
  11905. configurable: true
  11906. });
  11907. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11908. /** Defines that alpha blending to DEST - SRC * DEST */
  11909. get: function () {
  11910. return Engine._ALPHA_SUBTRACT;
  11911. },
  11912. enumerable: true,
  11913. configurable: true
  11914. });
  11915. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11916. /** Defines that alpha blending to SRC * DEST */
  11917. get: function () {
  11918. return Engine._ALPHA_MULTIPLY;
  11919. },
  11920. enumerable: true,
  11921. configurable: true
  11922. });
  11923. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11924. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11925. get: function () {
  11926. return Engine._ALPHA_MAXIMIZED;
  11927. },
  11928. enumerable: true,
  11929. configurable: true
  11930. });
  11931. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11932. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11933. get: function () {
  11934. return Engine._ALPHA_PREMULTIPLIED;
  11935. },
  11936. enumerable: true,
  11937. configurable: true
  11938. });
  11939. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11940. /**
  11941. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11942. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11943. */
  11944. get: function () {
  11945. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11946. },
  11947. enumerable: true,
  11948. configurable: true
  11949. });
  11950. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11951. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11952. get: function () {
  11953. return Engine._ALPHA_INTERPOLATE;
  11954. },
  11955. enumerable: true,
  11956. configurable: true
  11957. });
  11958. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11959. /**
  11960. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11961. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11962. */
  11963. get: function () {
  11964. return Engine._ALPHA_SCREENMODE;
  11965. },
  11966. enumerable: true,
  11967. configurable: true
  11968. });
  11969. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11970. // Delays
  11971. /** Defines that the ressource is not delayed*/
  11972. get: function () {
  11973. return Engine._DELAYLOADSTATE_NONE;
  11974. },
  11975. enumerable: true,
  11976. configurable: true
  11977. });
  11978. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11979. /** Defines that the ressource was successfully delay loaded */
  11980. get: function () {
  11981. return Engine._DELAYLOADSTATE_LOADED;
  11982. },
  11983. enumerable: true,
  11984. configurable: true
  11985. });
  11986. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11987. /** Defines that the ressource is currently delay loading */
  11988. get: function () {
  11989. return Engine._DELAYLOADSTATE_LOADING;
  11990. },
  11991. enumerable: true,
  11992. configurable: true
  11993. });
  11994. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11995. /** Defines that the ressource is delayed and has not started loading */
  11996. get: function () {
  11997. return Engine._DELAYLOADSTATE_NOTLOADED;
  11998. },
  11999. enumerable: true,
  12000. configurable: true
  12001. });
  12002. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12003. /** ALPHA */
  12004. get: function () {
  12005. return Engine._TEXTUREFORMAT_ALPHA;
  12006. },
  12007. enumerable: true,
  12008. configurable: true
  12009. });
  12010. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12011. /** LUMINANCE */
  12012. get: function () {
  12013. return Engine._TEXTUREFORMAT_LUMINANCE;
  12014. },
  12015. enumerable: true,
  12016. configurable: true
  12017. });
  12018. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12019. /**
  12020. * R
  12021. */
  12022. get: function () {
  12023. return Engine._TEXTUREFORMAT_R;
  12024. },
  12025. enumerable: true,
  12026. configurable: true
  12027. });
  12028. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12029. /**
  12030. * RG
  12031. */
  12032. get: function () {
  12033. return Engine._TEXTUREFORMAT_RG;
  12034. },
  12035. enumerable: true,
  12036. configurable: true
  12037. });
  12038. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12039. /** LUMINANCE_ALPHA */
  12040. get: function () {
  12041. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12042. },
  12043. enumerable: true,
  12044. configurable: true
  12045. });
  12046. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12047. /** RGB */
  12048. get: function () {
  12049. return Engine._TEXTUREFORMAT_RGB;
  12050. },
  12051. enumerable: true,
  12052. configurable: true
  12053. });
  12054. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12055. /** RGBA */
  12056. get: function () {
  12057. return Engine._TEXTUREFORMAT_RGBA;
  12058. },
  12059. enumerable: true,
  12060. configurable: true
  12061. });
  12062. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12063. /** UNSIGNED_INT */
  12064. get: function () {
  12065. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12066. },
  12067. enumerable: true,
  12068. configurable: true
  12069. });
  12070. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12071. /** FLOAT */
  12072. get: function () {
  12073. return Engine._TEXTURETYPE_FLOAT;
  12074. },
  12075. enumerable: true,
  12076. configurable: true
  12077. });
  12078. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12079. /** HALF_FLOAT */
  12080. get: function () {
  12081. return Engine._TEXTURETYPE_HALF_FLOAT;
  12082. },
  12083. enumerable: true,
  12084. configurable: true
  12085. });
  12086. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12087. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12088. get: function () {
  12089. return Engine._SCALEMODE_FLOOR;
  12090. },
  12091. enumerable: true,
  12092. configurable: true
  12093. });
  12094. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12095. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12096. get: function () {
  12097. return Engine._SCALEMODE_NEAREST;
  12098. },
  12099. enumerable: true,
  12100. configurable: true
  12101. });
  12102. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12103. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12104. get: function () {
  12105. return Engine._SCALEMODE_CEILING;
  12106. },
  12107. enumerable: true,
  12108. configurable: true
  12109. });
  12110. Object.defineProperty(Engine, "Version", {
  12111. /**
  12112. * Returns the current version of the framework
  12113. */
  12114. get: function () {
  12115. return "3.3.0-alpha.9";
  12116. },
  12117. enumerable: true,
  12118. configurable: true
  12119. });
  12120. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12121. /**
  12122. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12123. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12124. */
  12125. get: function () {
  12126. return this._vrExclusivePointerMode;
  12127. },
  12128. enumerable: true,
  12129. configurable: true
  12130. });
  12131. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12132. /**
  12133. * Gets a boolean indicating that the engine supports uniform buffers
  12134. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12135. */
  12136. get: function () {
  12137. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12138. },
  12139. enumerable: true,
  12140. configurable: true
  12141. });
  12142. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12143. /**
  12144. * Gets a boolean indicating that only power of 2 textures are supported
  12145. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12146. */
  12147. get: function () {
  12148. return this._webGLVersion < 2 || this.forcePOTTextures;
  12149. },
  12150. enumerable: true,
  12151. configurable: true
  12152. });
  12153. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12154. /**
  12155. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12156. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12157. */
  12158. get: function () {
  12159. return this._doNotHandleContextLost;
  12160. },
  12161. set: function (value) {
  12162. this._doNotHandleContextLost = value;
  12163. },
  12164. enumerable: true,
  12165. configurable: true
  12166. });
  12167. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12168. /**
  12169. * Gets the performance monitor attached to this engine
  12170. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12171. */
  12172. get: function () {
  12173. return this._performanceMonitor;
  12174. },
  12175. enumerable: true,
  12176. configurable: true
  12177. });
  12178. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12179. /**
  12180. * Gets the list of texture formats supported
  12181. */
  12182. get: function () {
  12183. return this._texturesSupported;
  12184. },
  12185. enumerable: true,
  12186. configurable: true
  12187. });
  12188. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12189. /**
  12190. * Gets the list of texture formats in use
  12191. */
  12192. get: function () {
  12193. return this._textureFormatInUse;
  12194. },
  12195. enumerable: true,
  12196. configurable: true
  12197. });
  12198. Object.defineProperty(Engine.prototype, "currentViewport", {
  12199. /**
  12200. * Gets the current viewport
  12201. */
  12202. get: function () {
  12203. return this._cachedViewport;
  12204. },
  12205. enumerable: true,
  12206. configurable: true
  12207. });
  12208. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12209. /**
  12210. * Gets the default empty texture
  12211. */
  12212. get: function () {
  12213. if (!this._emptyTexture) {
  12214. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12215. }
  12216. return this._emptyTexture;
  12217. },
  12218. enumerable: true,
  12219. configurable: true
  12220. });
  12221. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12222. /**
  12223. * Gets the default empty 3D texture
  12224. */
  12225. get: function () {
  12226. if (!this._emptyTexture3D) {
  12227. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12228. }
  12229. return this._emptyTexture3D;
  12230. },
  12231. enumerable: true,
  12232. configurable: true
  12233. });
  12234. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12235. /**
  12236. * Gets the default empty cube texture
  12237. */
  12238. get: function () {
  12239. if (!this._emptyCubeTexture) {
  12240. var faceData = new Uint8Array(4);
  12241. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12242. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12243. }
  12244. return this._emptyCubeTexture;
  12245. },
  12246. enumerable: true,
  12247. configurable: true
  12248. });
  12249. Engine.prototype._rebuildInternalTextures = function () {
  12250. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12251. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12252. var internalTexture = currentState_1[_i];
  12253. internalTexture._rebuild();
  12254. }
  12255. };
  12256. Engine.prototype._rebuildEffects = function () {
  12257. for (var key in this._compiledEffects) {
  12258. var effect = this._compiledEffects[key];
  12259. effect._prepareEffect();
  12260. }
  12261. BABYLON.Effect.ResetCache();
  12262. };
  12263. Engine.prototype._rebuildBuffers = function () {
  12264. // Index / Vertex
  12265. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12266. var scene = _a[_i];
  12267. scene.resetCachedMaterial();
  12268. scene._rebuildGeometries();
  12269. scene._rebuildTextures();
  12270. }
  12271. // Uniforms
  12272. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12273. var uniformBuffer = _c[_b];
  12274. uniformBuffer._rebuild();
  12275. }
  12276. };
  12277. Engine.prototype._initGLContext = function () {
  12278. // Caps
  12279. this._caps = new EngineCapabilities();
  12280. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12281. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12282. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12283. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12284. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12285. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12286. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12287. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12288. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12289. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12290. // Infos
  12291. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12292. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12293. if (rendererInfo != null) {
  12294. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12295. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12296. }
  12297. if (!this._glVendor) {
  12298. this._glVendor = "Unknown vendor";
  12299. }
  12300. if (!this._glRenderer) {
  12301. this._glRenderer = "Unknown renderer";
  12302. }
  12303. // Constants
  12304. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12305. if (this._gl.RGBA16F !== 0x881A) {
  12306. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12307. }
  12308. if (this._gl.RGBA32F !== 0x8814) {
  12309. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12310. }
  12311. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12312. this._gl.DEPTH24_STENCIL8 = 35056;
  12313. }
  12314. // Extensions
  12315. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12316. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12317. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12318. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12319. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12320. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12321. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12322. 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');
  12323. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12324. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12325. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12326. this._caps.highPrecisionShaderSupported = true;
  12327. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12328. if (this._caps.timerQuery) {
  12329. if (this._webGLVersion === 1) {
  12330. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12331. }
  12332. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12333. }
  12334. // Checks if some of the format renders first to allow the use of webgl inspector.
  12335. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12336. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12337. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12338. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12339. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12340. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12341. if (this._webGLVersion > 1) {
  12342. this._gl.HALF_FLOAT_OES = 0x140B;
  12343. }
  12344. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12345. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12346. // Draw buffers
  12347. if (this._webGLVersion > 1) {
  12348. this._caps.drawBuffersExtension = true;
  12349. }
  12350. else {
  12351. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12352. if (drawBuffersExtension !== null) {
  12353. this._caps.drawBuffersExtension = true;
  12354. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12355. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12356. for (var i = 0; i < 16; i++) {
  12357. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12358. }
  12359. }
  12360. else {
  12361. this._caps.drawBuffersExtension = false;
  12362. }
  12363. }
  12364. // Depth Texture
  12365. if (this._webGLVersion > 1) {
  12366. this._caps.depthTextureExtension = true;
  12367. }
  12368. else {
  12369. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12370. if (depthTextureExtension != null) {
  12371. this._caps.depthTextureExtension = true;
  12372. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12373. }
  12374. }
  12375. // Vertex array object
  12376. if (this._webGLVersion > 1) {
  12377. this._caps.vertexArrayObject = true;
  12378. }
  12379. else {
  12380. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12381. if (vertexArrayObjectExtension != null) {
  12382. this._caps.vertexArrayObject = true;
  12383. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12384. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12385. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12386. }
  12387. else {
  12388. this._caps.vertexArrayObject = false;
  12389. }
  12390. }
  12391. // Instances count
  12392. if (this._webGLVersion > 1) {
  12393. this._caps.instancedArrays = true;
  12394. }
  12395. else {
  12396. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12397. if (instanceExtension != null) {
  12398. this._caps.instancedArrays = true;
  12399. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12400. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12401. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12402. }
  12403. else {
  12404. this._caps.instancedArrays = false;
  12405. }
  12406. }
  12407. // Intelligently add supported compressed formats in order to check for.
  12408. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12409. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12410. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12411. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12412. if (this._caps.astc)
  12413. this.texturesSupported.push('-astc.ktx');
  12414. if (this._caps.s3tc)
  12415. this.texturesSupported.push('-dxt.ktx');
  12416. if (this._caps.pvrtc)
  12417. this.texturesSupported.push('-pvrtc.ktx');
  12418. if (this._caps.etc2)
  12419. this.texturesSupported.push('-etc2.ktx');
  12420. if (this._caps.etc1)
  12421. this.texturesSupported.push('-etc1.ktx');
  12422. if (this._gl.getShaderPrecisionFormat) {
  12423. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12424. if (highp) {
  12425. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12426. }
  12427. }
  12428. // Depth buffer
  12429. this.setDepthBuffer(true);
  12430. this.setDepthFunctionToLessOrEqual();
  12431. this.setDepthWrite(true);
  12432. // Texture maps
  12433. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12434. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12435. this._nextFreeTextureSlots.push(slot);
  12436. }
  12437. };
  12438. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12439. /**
  12440. * Gets version of the current webGL context
  12441. */
  12442. get: function () {
  12443. return this._webGLVersion;
  12444. },
  12445. enumerable: true,
  12446. configurable: true
  12447. });
  12448. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12449. /**
  12450. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12451. */
  12452. get: function () {
  12453. return this._isStencilEnable;
  12454. },
  12455. enumerable: true,
  12456. configurable: true
  12457. });
  12458. Engine.prototype._prepareWorkingCanvas = function () {
  12459. if (this._workingCanvas) {
  12460. return;
  12461. }
  12462. this._workingCanvas = document.createElement("canvas");
  12463. var context = this._workingCanvas.getContext("2d");
  12464. if (context) {
  12465. this._workingContext = context;
  12466. }
  12467. };
  12468. /**
  12469. * Reset the texture cache to empty state
  12470. */
  12471. Engine.prototype.resetTextureCache = function () {
  12472. for (var key in this._boundTexturesCache) {
  12473. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12474. continue;
  12475. }
  12476. var boundTexture = this._boundTexturesCache[key];
  12477. if (boundTexture) {
  12478. this._removeDesignatedSlot(boundTexture);
  12479. }
  12480. this._boundTexturesCache[key] = null;
  12481. }
  12482. if (!this.disableTextureBindingOptimization) {
  12483. this._nextFreeTextureSlots = [];
  12484. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12485. this._nextFreeTextureSlots.push(slot);
  12486. }
  12487. }
  12488. this._currentTextureChannel = -1;
  12489. };
  12490. /**
  12491. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12492. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12493. * @returns true if engine is in deterministic lock step mode
  12494. */
  12495. Engine.prototype.isDeterministicLockStep = function () {
  12496. return this._deterministicLockstep;
  12497. };
  12498. /**
  12499. * Gets the max steps when engine is running in deterministic lock step
  12500. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12501. * @returns the max steps
  12502. */
  12503. Engine.prototype.getLockstepMaxSteps = function () {
  12504. return this._lockstepMaxSteps;
  12505. };
  12506. /**
  12507. * Gets an object containing information about the current webGL context
  12508. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12509. */
  12510. Engine.prototype.getGlInfo = function () {
  12511. return {
  12512. vendor: this._glVendor,
  12513. renderer: this._glRenderer,
  12514. version: this._glVersion
  12515. };
  12516. };
  12517. /**
  12518. * Gets current aspect ratio
  12519. * @param camera defines the camera to use to get the aspect ratio
  12520. * @param useScreen defines if screen size must be used (or the current render target if any)
  12521. * @returns a number defining the aspect ratio
  12522. */
  12523. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12524. if (useScreen === void 0) { useScreen = false; }
  12525. var viewport = camera.viewport;
  12526. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12527. };
  12528. /**
  12529. * Gets current screen aspect ratio
  12530. * @returns a number defining the aspect ratio
  12531. */
  12532. Engine.prototype.getScreenAspectRatio = function () {
  12533. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12534. };
  12535. /**
  12536. * Gets the current render width
  12537. * @param useScreen defines if screen size must be used (or the current render target if any)
  12538. * @returns a number defining the current render width
  12539. */
  12540. Engine.prototype.getRenderWidth = function (useScreen) {
  12541. if (useScreen === void 0) { useScreen = false; }
  12542. if (!useScreen && this._currentRenderTarget) {
  12543. return this._currentRenderTarget.width;
  12544. }
  12545. return this._gl.drawingBufferWidth;
  12546. };
  12547. /**
  12548. * Gets the current render height
  12549. * @param useScreen defines if screen size must be used (or the current render target if any)
  12550. * @returns a number defining the current render height
  12551. */
  12552. Engine.prototype.getRenderHeight = function (useScreen) {
  12553. if (useScreen === void 0) { useScreen = false; }
  12554. if (!useScreen && this._currentRenderTarget) {
  12555. return this._currentRenderTarget.height;
  12556. }
  12557. return this._gl.drawingBufferHeight;
  12558. };
  12559. /**
  12560. * Gets the HTML canvas attached with the current webGL context
  12561. * @returns a HTML canvas
  12562. */
  12563. Engine.prototype.getRenderingCanvas = function () {
  12564. return this._renderingCanvas;
  12565. };
  12566. /**
  12567. * Gets the client rect of the HTML canvas attached with the current webGL context
  12568. * @returns a client rectanglee
  12569. */
  12570. Engine.prototype.getRenderingCanvasClientRect = function () {
  12571. if (!this._renderingCanvas) {
  12572. return null;
  12573. }
  12574. return this._renderingCanvas.getBoundingClientRect();
  12575. };
  12576. /**
  12577. * Defines the hardware scaling level.
  12578. * By default the hardware scaling level is computed from the window device ratio.
  12579. * 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.
  12580. * @param level defines the level to use
  12581. */
  12582. Engine.prototype.setHardwareScalingLevel = function (level) {
  12583. this._hardwareScalingLevel = level;
  12584. this.resize();
  12585. };
  12586. /**
  12587. * Gets the current hardware scaling level.
  12588. * By default the hardware scaling level is computed from the window device ratio.
  12589. * 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.
  12590. * @returns a number indicating the current hardware scaling level
  12591. */
  12592. Engine.prototype.getHardwareScalingLevel = function () {
  12593. return this._hardwareScalingLevel;
  12594. };
  12595. /**
  12596. * Gets the list of loaded textures
  12597. * @returns an array containing all loaded textures
  12598. */
  12599. Engine.prototype.getLoadedTexturesCache = function () {
  12600. return this._internalTexturesCache;
  12601. };
  12602. /**
  12603. * Gets the object containing all engine capabilities
  12604. * @returns the EngineCapabilities object
  12605. */
  12606. Engine.prototype.getCaps = function () {
  12607. return this._caps;
  12608. };
  12609. Object.defineProperty(Engine.prototype, "drawCalls", {
  12610. /** @hidden */
  12611. get: function () {
  12612. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12613. return 0;
  12614. },
  12615. enumerable: true,
  12616. configurable: true
  12617. });
  12618. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12619. /** @hidden */
  12620. get: function () {
  12621. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12622. return null;
  12623. },
  12624. enumerable: true,
  12625. configurable: true
  12626. });
  12627. /**
  12628. * Gets the current depth function
  12629. * @returns a number defining the depth function
  12630. */
  12631. Engine.prototype.getDepthFunction = function () {
  12632. return this._depthCullingState.depthFunc;
  12633. };
  12634. /**
  12635. * Sets the current depth function
  12636. * @param depthFunc defines the function to use
  12637. */
  12638. Engine.prototype.setDepthFunction = function (depthFunc) {
  12639. this._depthCullingState.depthFunc = depthFunc;
  12640. };
  12641. /**
  12642. * Sets the current depth function to GREATER
  12643. */
  12644. Engine.prototype.setDepthFunctionToGreater = function () {
  12645. this._depthCullingState.depthFunc = this._gl.GREATER;
  12646. };
  12647. /**
  12648. * Sets the current depth function to GEQUAL
  12649. */
  12650. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12651. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12652. };
  12653. /**
  12654. * Sets the current depth function to LESS
  12655. */
  12656. Engine.prototype.setDepthFunctionToLess = function () {
  12657. this._depthCullingState.depthFunc = this._gl.LESS;
  12658. };
  12659. /**
  12660. * Sets the current depth function to LEQUAL
  12661. */
  12662. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12663. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12664. };
  12665. /**
  12666. * Gets a boolean indicating if stencil buffer is enabled
  12667. * @returns the current stencil buffer state
  12668. */
  12669. Engine.prototype.getStencilBuffer = function () {
  12670. return this._stencilState.stencilTest;
  12671. };
  12672. /**
  12673. * Enable or disable the stencil buffer
  12674. * @param enable defines if the stencil buffer must be enabled or disabled
  12675. */
  12676. Engine.prototype.setStencilBuffer = function (enable) {
  12677. this._stencilState.stencilTest = enable;
  12678. };
  12679. /**
  12680. * Gets the current stencil mask
  12681. * @returns a number defining the new stencil mask to use
  12682. */
  12683. Engine.prototype.getStencilMask = function () {
  12684. return this._stencilState.stencilMask;
  12685. };
  12686. /**
  12687. * Sets the current stencil mask
  12688. * @param mask defines the new stencil mask to use
  12689. */
  12690. Engine.prototype.setStencilMask = function (mask) {
  12691. this._stencilState.stencilMask = mask;
  12692. };
  12693. /**
  12694. * Gets the current stencil function
  12695. * @returns a number defining the stencil function to use
  12696. */
  12697. Engine.prototype.getStencilFunction = function () {
  12698. return this._stencilState.stencilFunc;
  12699. };
  12700. /**
  12701. * Gets the current stencil reference value
  12702. * @returns a number defining the stencil reference value to use
  12703. */
  12704. Engine.prototype.getStencilFunctionReference = function () {
  12705. return this._stencilState.stencilFuncRef;
  12706. };
  12707. /**
  12708. * Gets the current stencil mask
  12709. * @returns a number defining the stencil mask to use
  12710. */
  12711. Engine.prototype.getStencilFunctionMask = function () {
  12712. return this._stencilState.stencilFuncMask;
  12713. };
  12714. /**
  12715. * Sets the current stencil function
  12716. * @param stencilFunc defines the new stencil function to use
  12717. */
  12718. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12719. this._stencilState.stencilFunc = stencilFunc;
  12720. };
  12721. /**
  12722. * Sets the current stencil reference
  12723. * @param reference defines the new stencil reference to use
  12724. */
  12725. Engine.prototype.setStencilFunctionReference = function (reference) {
  12726. this._stencilState.stencilFuncRef = reference;
  12727. };
  12728. /**
  12729. * Sets the current stencil mask
  12730. * @param mask defines the new stencil mask to use
  12731. */
  12732. Engine.prototype.setStencilFunctionMask = function (mask) {
  12733. this._stencilState.stencilFuncMask = mask;
  12734. };
  12735. /**
  12736. * Gets the current stencil operation when stencil fails
  12737. * @returns a number defining stencil operation to use when stencil fails
  12738. */
  12739. Engine.prototype.getStencilOperationFail = function () {
  12740. return this._stencilState.stencilOpStencilFail;
  12741. };
  12742. /**
  12743. * Gets the current stencil operation when depth fails
  12744. * @returns a number defining stencil operation to use when depth fails
  12745. */
  12746. Engine.prototype.getStencilOperationDepthFail = function () {
  12747. return this._stencilState.stencilOpDepthFail;
  12748. };
  12749. /**
  12750. * Gets the current stencil operation when stencil passes
  12751. * @returns a number defining stencil operation to use when stencil passes
  12752. */
  12753. Engine.prototype.getStencilOperationPass = function () {
  12754. return this._stencilState.stencilOpStencilDepthPass;
  12755. };
  12756. /**
  12757. * Sets the stencil operation to use when stencil fails
  12758. * @param operation defines the stencil operation to use when stencil fails
  12759. */
  12760. Engine.prototype.setStencilOperationFail = function (operation) {
  12761. this._stencilState.stencilOpStencilFail = operation;
  12762. };
  12763. /**
  12764. * Sets the stencil operation to use when depth fails
  12765. * @param operation defines the stencil operation to use when depth fails
  12766. */
  12767. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12768. this._stencilState.stencilOpDepthFail = operation;
  12769. };
  12770. /**
  12771. * Sets the stencil operation to use when stencil passes
  12772. * @param operation defines the stencil operation to use when stencil passes
  12773. */
  12774. Engine.prototype.setStencilOperationPass = function (operation) {
  12775. this._stencilState.stencilOpStencilDepthPass = operation;
  12776. };
  12777. /**
  12778. * Sets a boolean indicating if the dithering state is enabled or disabled
  12779. * @param value defines the dithering state
  12780. */
  12781. Engine.prototype.setDitheringState = function (value) {
  12782. if (value) {
  12783. this._gl.enable(this._gl.DITHER);
  12784. }
  12785. else {
  12786. this._gl.disable(this._gl.DITHER);
  12787. }
  12788. };
  12789. /**
  12790. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12791. * @param value defines the rasterizer state
  12792. */
  12793. Engine.prototype.setRasterizerState = function (value) {
  12794. if (value) {
  12795. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12796. }
  12797. else {
  12798. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12799. }
  12800. };
  12801. /**
  12802. * stop executing a render loop function and remove it from the execution array
  12803. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12804. */
  12805. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12806. if (!renderFunction) {
  12807. this._activeRenderLoops = [];
  12808. return;
  12809. }
  12810. var index = this._activeRenderLoops.indexOf(renderFunction);
  12811. if (index >= 0) {
  12812. this._activeRenderLoops.splice(index, 1);
  12813. }
  12814. };
  12815. /** @hidden */
  12816. Engine.prototype._renderLoop = function () {
  12817. if (!this._contextWasLost) {
  12818. var shouldRender = true;
  12819. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12820. shouldRender = false;
  12821. }
  12822. if (shouldRender) {
  12823. // Start new frame
  12824. this.beginFrame();
  12825. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12826. var renderFunction = this._activeRenderLoops[index];
  12827. renderFunction();
  12828. }
  12829. // Present
  12830. this.endFrame();
  12831. }
  12832. }
  12833. if (this._activeRenderLoops.length > 0) {
  12834. // Register new frame
  12835. var requester = null;
  12836. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12837. requester = this._vrDisplay;
  12838. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12839. }
  12840. else {
  12841. this._renderingQueueLaunched = false;
  12842. }
  12843. };
  12844. /**
  12845. * Register and execute a render loop. The engine can have more than one render function
  12846. * @param renderFunction defines the function to continuously execute
  12847. */
  12848. Engine.prototype.runRenderLoop = function (renderFunction) {
  12849. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12850. return;
  12851. }
  12852. this._activeRenderLoops.push(renderFunction);
  12853. if (!this._renderingQueueLaunched) {
  12854. this._renderingQueueLaunched = true;
  12855. this._bindedRenderFunction = this._renderLoop.bind(this);
  12856. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12857. }
  12858. };
  12859. /**
  12860. * Toggle full screen mode
  12861. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12862. * @param options defines an option object to be sent to the requestFullscreen function
  12863. */
  12864. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12865. if (this.isFullscreen) {
  12866. BABYLON.Tools.ExitFullscreen();
  12867. }
  12868. else {
  12869. this._pointerLockRequested = requestPointerLock;
  12870. if (this._renderingCanvas) {
  12871. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12872. }
  12873. }
  12874. };
  12875. /**
  12876. * Clear the current render buffer or the current render target (if any is set up)
  12877. * @param color defines the color to use
  12878. * @param backBuffer defines if the back buffer must be cleared
  12879. * @param depth defines if the depth buffer must be cleared
  12880. * @param stencil defines if the stencil buffer must be cleared
  12881. */
  12882. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12883. if (stencil === void 0) { stencil = false; }
  12884. this.applyStates();
  12885. var mode = 0;
  12886. if (backBuffer && color) {
  12887. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12888. mode |= this._gl.COLOR_BUFFER_BIT;
  12889. }
  12890. if (depth) {
  12891. this._gl.clearDepth(1.0);
  12892. mode |= this._gl.DEPTH_BUFFER_BIT;
  12893. }
  12894. if (stencil) {
  12895. this._gl.clearStencil(0);
  12896. mode |= this._gl.STENCIL_BUFFER_BIT;
  12897. }
  12898. this._gl.clear(mode);
  12899. };
  12900. /**
  12901. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12902. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12903. * @param y defines the y-coordinate of the corner of the clear rectangle
  12904. * @param width defines the width of the clear rectangle
  12905. * @param height defines the height of the clear rectangle
  12906. * @param clearColor defines the clear color
  12907. */
  12908. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12909. var gl = this._gl;
  12910. // Save state
  12911. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12912. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12913. // Change state
  12914. gl.enable(gl.SCISSOR_TEST);
  12915. gl.scissor(x, y, width, height);
  12916. // Clear
  12917. this.clear(clearColor, true, true, true);
  12918. // Restore state
  12919. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12920. if (curScissor === true) {
  12921. gl.enable(gl.SCISSOR_TEST);
  12922. }
  12923. else {
  12924. gl.disable(gl.SCISSOR_TEST);
  12925. }
  12926. };
  12927. /** @hidden */
  12928. Engine.prototype._viewport = function (x, y, width, height) {
  12929. if (x !== this._viewportCached.x ||
  12930. y !== this._viewportCached.y ||
  12931. width !== this._viewportCached.z ||
  12932. height !== this._viewportCached.w) {
  12933. this._viewportCached.x = x;
  12934. this._viewportCached.y = y;
  12935. this._viewportCached.z = width;
  12936. this._viewportCached.w = height;
  12937. this._gl.viewport(x, y, width, height);
  12938. }
  12939. };
  12940. /**
  12941. * Set the WebGL's viewport
  12942. * @param viewport defines the viewport element to be used
  12943. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12944. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12945. */
  12946. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12947. var width = requiredWidth || this.getRenderWidth();
  12948. var height = requiredHeight || this.getRenderHeight();
  12949. var x = viewport.x || 0;
  12950. var y = viewport.y || 0;
  12951. this._cachedViewport = viewport;
  12952. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12953. };
  12954. /**
  12955. * Directly set the WebGL Viewport
  12956. * @param x defines the x coordinate of the viewport (in screen space)
  12957. * @param y defines the y coordinate of the viewport (in screen space)
  12958. * @param width defines the width of the viewport (in screen space)
  12959. * @param height defines the height of the viewport (in screen space)
  12960. * @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
  12961. */
  12962. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12963. var currentViewport = this._cachedViewport;
  12964. this._cachedViewport = null;
  12965. this._viewport(x, y, width, height);
  12966. return currentViewport;
  12967. };
  12968. /**
  12969. * Begin a new frame
  12970. */
  12971. Engine.prototype.beginFrame = function () {
  12972. this.onBeginFrameObservable.notifyObservers(this);
  12973. this._measureFps();
  12974. };
  12975. /**
  12976. * Enf the current frame
  12977. */
  12978. Engine.prototype.endFrame = function () {
  12979. // Force a flush in case we are using a bad OS.
  12980. if (this._badOS) {
  12981. this.flushFramebuffer();
  12982. }
  12983. // Submit frame to the vr device, if enabled
  12984. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12985. // TODO: We should only submit the frame if we read frameData successfully.
  12986. this._vrDisplay.submitFrame();
  12987. }
  12988. this.onEndFrameObservable.notifyObservers(this);
  12989. };
  12990. /**
  12991. * Resize the view according to the canvas' size
  12992. */
  12993. Engine.prototype.resize = function () {
  12994. // We're not resizing the size of the canvas while in VR mode & presenting
  12995. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12996. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12997. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12998. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12999. }
  13000. };
  13001. /**
  13002. * Force a specific size of the canvas
  13003. * @param width defines the new canvas' width
  13004. * @param height defines the new canvas' height
  13005. */
  13006. Engine.prototype.setSize = function (width, height) {
  13007. if (!this._renderingCanvas) {
  13008. return;
  13009. }
  13010. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13011. return;
  13012. }
  13013. this._renderingCanvas.width = width;
  13014. this._renderingCanvas.height = height;
  13015. for (var index = 0; index < this.scenes.length; index++) {
  13016. var scene = this.scenes[index];
  13017. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13018. var cam = scene.cameras[camIndex];
  13019. cam._currentRenderId = 0;
  13020. }
  13021. }
  13022. if (this.onResizeObservable.hasObservers) {
  13023. this.onResizeObservable.notifyObservers(this);
  13024. }
  13025. };
  13026. // WebVR functions
  13027. /**
  13028. * Gets a boolean indicating if a webVR device was detected
  13029. * @returns true if a webVR device was detected
  13030. */
  13031. Engine.prototype.isVRDevicePresent = function () {
  13032. return !!this._vrDisplay;
  13033. };
  13034. /**
  13035. * Gets the current webVR device
  13036. * @returns the current webVR device (or null)
  13037. */
  13038. Engine.prototype.getVRDevice = function () {
  13039. return this._vrDisplay;
  13040. };
  13041. /**
  13042. * Initializes a webVR display and starts listening to display change events
  13043. * The onVRDisplayChangedObservable will be notified upon these changes
  13044. * @returns The onVRDisplayChangedObservable
  13045. */
  13046. Engine.prototype.initWebVR = function () {
  13047. this.initWebVRAsync();
  13048. return this.onVRDisplayChangedObservable;
  13049. };
  13050. /**
  13051. * Initializes a webVR display and starts listening to display change events
  13052. * The onVRDisplayChangedObservable will be notified upon these changes
  13053. * @returns A promise containing a VRDisplay and if vr is supported
  13054. */
  13055. Engine.prototype.initWebVRAsync = function () {
  13056. var _this = this;
  13057. var notifyObservers = function () {
  13058. var eventArgs = {
  13059. vrDisplay: _this._vrDisplay,
  13060. vrSupported: _this._vrSupported
  13061. };
  13062. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13063. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13064. };
  13065. if (!this._onVrDisplayConnect) {
  13066. this._onVrDisplayConnect = function (event) {
  13067. _this._vrDisplay = event.display;
  13068. notifyObservers();
  13069. };
  13070. this._onVrDisplayDisconnect = function () {
  13071. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13072. _this._vrDisplay = undefined;
  13073. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13074. notifyObservers();
  13075. };
  13076. this._onVrDisplayPresentChange = function () {
  13077. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13078. };
  13079. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13080. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13081. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13082. }
  13083. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13084. this._webVRInitPromise.then(notifyObservers);
  13085. return this._webVRInitPromise;
  13086. };
  13087. /**
  13088. * Call this function to switch to webVR mode
  13089. * Will do nothing if webVR is not supported or if there is no webVR device
  13090. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13091. */
  13092. Engine.prototype.enableVR = function () {
  13093. var _this = this;
  13094. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13095. var onResolved = function () {
  13096. _this.onVRRequestPresentComplete.notifyObservers(true);
  13097. _this._onVRFullScreenTriggered();
  13098. };
  13099. var onRejected = function () {
  13100. _this.onVRRequestPresentComplete.notifyObservers(false);
  13101. };
  13102. this.onVRRequestPresentStart.notifyObservers(this);
  13103. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13104. }
  13105. };
  13106. /**
  13107. * Call this function to leave webVR mode
  13108. * Will do nothing if webVR is not supported or if there is no webVR device
  13109. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13110. */
  13111. Engine.prototype.disableVR = function () {
  13112. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13113. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13114. }
  13115. };
  13116. Engine.prototype._getVRDisplaysAsync = function () {
  13117. var _this = this;
  13118. return new Promise(function (res, rej) {
  13119. if (navigator.getVRDisplays) {
  13120. navigator.getVRDisplays().then(function (devices) {
  13121. _this._vrSupported = true;
  13122. // note that devices may actually be an empty array. This is fine;
  13123. // we expect this._vrDisplay to be undefined in this case.
  13124. _this._vrDisplay = devices[0];
  13125. res({
  13126. vrDisplay: _this._vrDisplay,
  13127. vrSupported: _this._vrSupported
  13128. });
  13129. });
  13130. }
  13131. else {
  13132. _this._vrDisplay = undefined;
  13133. _this._vrSupported = false;
  13134. res({
  13135. vrDisplay: _this._vrDisplay,
  13136. vrSupported: _this._vrSupported
  13137. });
  13138. }
  13139. });
  13140. };
  13141. /**
  13142. * Binds the frame buffer to the specified texture.
  13143. * @param texture The texture to render to or null for the default canvas
  13144. * @param faceIndex The face of the texture to render to in case of cube texture
  13145. * @param requiredWidth The width of the target to render to
  13146. * @param requiredHeight The height of the target to render to
  13147. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13148. * @param depthStencilTexture The depth stencil texture to use to render
  13149. * @param lodLevel defines le lod level to bind to the frame buffer
  13150. */
  13151. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13152. if (lodLevel === void 0) { lodLevel = 0; }
  13153. if (this._currentRenderTarget) {
  13154. this.unBindFramebuffer(this._currentRenderTarget);
  13155. }
  13156. this._currentRenderTarget = texture;
  13157. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13158. var gl = this._gl;
  13159. if (texture.isCube) {
  13160. if (faceIndex === undefined) {
  13161. faceIndex = 0;
  13162. }
  13163. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13164. if (depthStencilTexture) {
  13165. if (depthStencilTexture._generateStencilBuffer) {
  13166. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13167. }
  13168. else {
  13169. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13170. }
  13171. }
  13172. }
  13173. if (this._cachedViewport && !forceFullscreenViewport) {
  13174. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13175. }
  13176. else {
  13177. if (!requiredWidth) {
  13178. requiredWidth = texture.width;
  13179. if (lodLevel) {
  13180. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13181. }
  13182. }
  13183. if (!requiredHeight) {
  13184. requiredHeight = texture.height;
  13185. if (lodLevel) {
  13186. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13187. }
  13188. }
  13189. this._viewport(0, 0, requiredWidth, requiredHeight);
  13190. }
  13191. this.wipeCaches();
  13192. };
  13193. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13194. if (this._currentFramebuffer !== framebuffer) {
  13195. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13196. this._currentFramebuffer = framebuffer;
  13197. }
  13198. };
  13199. /**
  13200. * Unbind the current render target texture from the webGL context
  13201. * @param texture defines the render target texture to unbind
  13202. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13203. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13204. */
  13205. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13206. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13207. this._currentRenderTarget = null;
  13208. // If MSAA, we need to bitblt back to main texture
  13209. var gl = this._gl;
  13210. if (texture._MSAAFramebuffer) {
  13211. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13212. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13213. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13214. }
  13215. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13216. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13217. gl.generateMipmap(gl.TEXTURE_2D);
  13218. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13219. }
  13220. if (onBeforeUnbind) {
  13221. if (texture._MSAAFramebuffer) {
  13222. // Bind the correct framebuffer
  13223. this.bindUnboundFramebuffer(texture._framebuffer);
  13224. }
  13225. onBeforeUnbind();
  13226. }
  13227. this.bindUnboundFramebuffer(null);
  13228. };
  13229. /**
  13230. * Unbind a list of render target textures from the webGL context
  13231. * This is used only when drawBuffer extension or webGL2 are active
  13232. * @param textures defines the render target textures to unbind
  13233. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13234. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13235. */
  13236. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13237. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13238. this._currentRenderTarget = null;
  13239. // If MSAA, we need to bitblt back to main texture
  13240. var gl = this._gl;
  13241. if (textures[0]._MSAAFramebuffer) {
  13242. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13243. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13244. var attachments = textures[0]._attachments;
  13245. if (!attachments) {
  13246. attachments = new Array(textures.length);
  13247. textures[0]._attachments = attachments;
  13248. }
  13249. for (var i = 0; i < textures.length; i++) {
  13250. var texture = textures[i];
  13251. for (var j = 0; j < attachments.length; j++) {
  13252. attachments[j] = gl.NONE;
  13253. }
  13254. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13255. gl.readBuffer(attachments[i]);
  13256. gl.drawBuffers(attachments);
  13257. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13258. }
  13259. for (var i = 0; i < attachments.length; i++) {
  13260. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13261. }
  13262. gl.drawBuffers(attachments);
  13263. }
  13264. for (var i = 0; i < textures.length; i++) {
  13265. var texture = textures[i];
  13266. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13267. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13268. gl.generateMipmap(gl.TEXTURE_2D);
  13269. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13270. }
  13271. }
  13272. if (onBeforeUnbind) {
  13273. if (textures[0]._MSAAFramebuffer) {
  13274. // Bind the correct framebuffer
  13275. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13276. }
  13277. onBeforeUnbind();
  13278. }
  13279. this.bindUnboundFramebuffer(null);
  13280. };
  13281. /**
  13282. * Force the mipmap generation for the given render target texture
  13283. * @param texture defines the render target texture to use
  13284. */
  13285. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13286. if (texture.generateMipMaps) {
  13287. var gl = this._gl;
  13288. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13289. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13290. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13291. }
  13292. };
  13293. /**
  13294. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13295. */
  13296. Engine.prototype.flushFramebuffer = function () {
  13297. this._gl.flush();
  13298. };
  13299. /**
  13300. * Unbind the current render target and bind the default framebuffer
  13301. */
  13302. Engine.prototype.restoreDefaultFramebuffer = function () {
  13303. if (this._currentRenderTarget) {
  13304. this.unBindFramebuffer(this._currentRenderTarget);
  13305. }
  13306. else {
  13307. this.bindUnboundFramebuffer(null);
  13308. }
  13309. if (this._cachedViewport) {
  13310. this.setViewport(this._cachedViewport);
  13311. }
  13312. this.wipeCaches();
  13313. };
  13314. // UBOs
  13315. /**
  13316. * Create an uniform buffer
  13317. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13318. * @param elements defines the content of the uniform buffer
  13319. * @returns the webGL uniform buffer
  13320. */
  13321. Engine.prototype.createUniformBuffer = function (elements) {
  13322. var ubo = this._gl.createBuffer();
  13323. if (!ubo) {
  13324. throw new Error("Unable to create uniform buffer");
  13325. }
  13326. this.bindUniformBuffer(ubo);
  13327. if (elements instanceof Float32Array) {
  13328. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13329. }
  13330. else {
  13331. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13332. }
  13333. this.bindUniformBuffer(null);
  13334. ubo.references = 1;
  13335. return ubo;
  13336. };
  13337. /**
  13338. * Create a dynamic uniform buffer
  13339. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13340. * @param elements defines the content of the uniform buffer
  13341. * @returns the webGL uniform buffer
  13342. */
  13343. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13344. var ubo = this._gl.createBuffer();
  13345. if (!ubo) {
  13346. throw new Error("Unable to create dynamic uniform buffer");
  13347. }
  13348. this.bindUniformBuffer(ubo);
  13349. if (elements instanceof Float32Array) {
  13350. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13351. }
  13352. else {
  13353. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13354. }
  13355. this.bindUniformBuffer(null);
  13356. ubo.references = 1;
  13357. return ubo;
  13358. };
  13359. /**
  13360. * Update an existing uniform buffer
  13361. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13362. * @param uniformBuffer defines the target uniform buffer
  13363. * @param elements defines the content to update
  13364. * @param offset defines the offset in the uniform buffer where update should start
  13365. * @param count defines the size of the data to update
  13366. */
  13367. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13368. this.bindUniformBuffer(uniformBuffer);
  13369. if (offset === undefined) {
  13370. offset = 0;
  13371. }
  13372. if (count === undefined) {
  13373. if (elements instanceof Float32Array) {
  13374. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13375. }
  13376. else {
  13377. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13378. }
  13379. }
  13380. else {
  13381. if (elements instanceof Float32Array) {
  13382. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13383. }
  13384. else {
  13385. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13386. }
  13387. }
  13388. this.bindUniformBuffer(null);
  13389. };
  13390. // VBOs
  13391. Engine.prototype._resetVertexBufferBinding = function () {
  13392. this.bindArrayBuffer(null);
  13393. this._cachedVertexBuffers = null;
  13394. };
  13395. /**
  13396. * Creates a vertex buffer
  13397. * @param data the data for the vertex buffer
  13398. * @returns the new WebGL static buffer
  13399. */
  13400. Engine.prototype.createVertexBuffer = function (data) {
  13401. var vbo = this._gl.createBuffer();
  13402. if (!vbo) {
  13403. throw new Error("Unable to create vertex buffer");
  13404. }
  13405. this.bindArrayBuffer(vbo);
  13406. if (data instanceof Array) {
  13407. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13408. }
  13409. else {
  13410. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13411. }
  13412. this._resetVertexBufferBinding();
  13413. vbo.references = 1;
  13414. return vbo;
  13415. };
  13416. /**
  13417. * Creates a dynamic vertex buffer
  13418. * @param data the data for the dynamic vertex buffer
  13419. * @returns the new WebGL dynamic buffer
  13420. */
  13421. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13422. var vbo = this._gl.createBuffer();
  13423. if (!vbo) {
  13424. throw new Error("Unable to create dynamic vertex buffer");
  13425. }
  13426. this.bindArrayBuffer(vbo);
  13427. if (data instanceof Array) {
  13428. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13429. }
  13430. else {
  13431. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13432. }
  13433. this._resetVertexBufferBinding();
  13434. vbo.references = 1;
  13435. return vbo;
  13436. };
  13437. /**
  13438. * Update a dynamic index buffer
  13439. * @param indexBuffer defines the target index buffer
  13440. * @param indices defines the data to update
  13441. * @param offset defines the offset in the target index buffer where update should start
  13442. */
  13443. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13444. if (offset === void 0) { offset = 0; }
  13445. // Force cache update
  13446. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13447. this.bindIndexBuffer(indexBuffer);
  13448. var arrayBuffer;
  13449. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13450. arrayBuffer = indices;
  13451. }
  13452. else {
  13453. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13454. }
  13455. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13456. this._resetIndexBufferBinding();
  13457. };
  13458. /**
  13459. * Updates a dynamic vertex buffer.
  13460. * @param vertexBuffer the vertex buffer to update
  13461. * @param data the data used to update the vertex buffer
  13462. * @param byteOffset the byte offset of the data
  13463. * @param byteLength the byte length of the data
  13464. */
  13465. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13466. this.bindArrayBuffer(vertexBuffer);
  13467. if (byteOffset === undefined) {
  13468. byteOffset = 0;
  13469. }
  13470. if (byteLength === undefined) {
  13471. if (data instanceof Array) {
  13472. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13473. }
  13474. else {
  13475. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13476. }
  13477. }
  13478. else {
  13479. if (data instanceof Array) {
  13480. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13481. }
  13482. else {
  13483. if (data instanceof ArrayBuffer) {
  13484. data = new Uint8Array(data, byteOffset, byteLength);
  13485. }
  13486. else {
  13487. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13488. }
  13489. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13490. }
  13491. }
  13492. this._resetVertexBufferBinding();
  13493. };
  13494. Engine.prototype._resetIndexBufferBinding = function () {
  13495. this.bindIndexBuffer(null);
  13496. this._cachedIndexBuffer = null;
  13497. };
  13498. /**
  13499. * Creates a new index buffer
  13500. * @param indices defines the content of the index buffer
  13501. * @param updatable defines if the index buffer must be updatable
  13502. * @returns a new webGL buffer
  13503. */
  13504. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13505. var vbo = this._gl.createBuffer();
  13506. if (!vbo) {
  13507. throw new Error("Unable to create index buffer");
  13508. }
  13509. this.bindIndexBuffer(vbo);
  13510. // Check for 32 bits indices
  13511. var arrayBuffer;
  13512. var need32Bits = false;
  13513. if (indices instanceof Uint16Array) {
  13514. arrayBuffer = indices;
  13515. }
  13516. else {
  13517. //check 32 bit support
  13518. if (this._caps.uintIndices) {
  13519. if (indices instanceof Uint32Array) {
  13520. arrayBuffer = indices;
  13521. need32Bits = true;
  13522. }
  13523. else {
  13524. //number[] or Int32Array, check if 32 bit is necessary
  13525. for (var index = 0; index < indices.length; index++) {
  13526. if (indices[index] > 65535) {
  13527. need32Bits = true;
  13528. break;
  13529. }
  13530. }
  13531. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13532. }
  13533. }
  13534. else {
  13535. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13536. arrayBuffer = new Uint16Array(indices);
  13537. }
  13538. }
  13539. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13540. this._resetIndexBufferBinding();
  13541. vbo.references = 1;
  13542. vbo.is32Bits = need32Bits;
  13543. return vbo;
  13544. };
  13545. /**
  13546. * Bind a webGL buffer to the webGL context
  13547. * @param buffer defines the buffer to bind
  13548. */
  13549. Engine.prototype.bindArrayBuffer = function (buffer) {
  13550. if (!this._vaoRecordInProgress) {
  13551. this._unbindVertexArrayObject();
  13552. }
  13553. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13554. };
  13555. /**
  13556. * Bind an uniform buffer to the current webGL context
  13557. * @param buffer defines the buffer to bind
  13558. */
  13559. Engine.prototype.bindUniformBuffer = function (buffer) {
  13560. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13561. };
  13562. /**
  13563. * Bind a buffer to the current webGL context at a given location
  13564. * @param buffer defines the buffer to bind
  13565. * @param location defines the index where to bind the buffer
  13566. */
  13567. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13568. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13569. };
  13570. /**
  13571. * Bind a specific block at a given index in a specific shader program
  13572. * @param shaderProgram defines the shader program
  13573. * @param blockName defines the block name
  13574. * @param index defines the index where to bind the block
  13575. */
  13576. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13577. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13578. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13579. };
  13580. ;
  13581. Engine.prototype.bindIndexBuffer = function (buffer) {
  13582. if (!this._vaoRecordInProgress) {
  13583. this._unbindVertexArrayObject();
  13584. }
  13585. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13586. };
  13587. Engine.prototype.bindBuffer = function (buffer, target) {
  13588. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13589. this._gl.bindBuffer(target, buffer);
  13590. this._currentBoundBuffer[target] = buffer;
  13591. }
  13592. };
  13593. /**
  13594. * update the bound buffer with the given data
  13595. * @param data defines the data to update
  13596. */
  13597. Engine.prototype.updateArrayBuffer = function (data) {
  13598. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13599. };
  13600. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13601. var pointer = this._currentBufferPointers[indx];
  13602. var changed = false;
  13603. if (!pointer.active) {
  13604. changed = true;
  13605. pointer.active = true;
  13606. pointer.index = indx;
  13607. pointer.size = size;
  13608. pointer.type = type;
  13609. pointer.normalized = normalized;
  13610. pointer.stride = stride;
  13611. pointer.offset = offset;
  13612. pointer.buffer = buffer;
  13613. }
  13614. else {
  13615. if (pointer.buffer !== buffer) {
  13616. pointer.buffer = buffer;
  13617. changed = true;
  13618. }
  13619. if (pointer.size !== size) {
  13620. pointer.size = size;
  13621. changed = true;
  13622. }
  13623. if (pointer.type !== type) {
  13624. pointer.type = type;
  13625. changed = true;
  13626. }
  13627. if (pointer.normalized !== normalized) {
  13628. pointer.normalized = normalized;
  13629. changed = true;
  13630. }
  13631. if (pointer.stride !== stride) {
  13632. pointer.stride = stride;
  13633. changed = true;
  13634. }
  13635. if (pointer.offset !== offset) {
  13636. pointer.offset = offset;
  13637. changed = true;
  13638. }
  13639. }
  13640. if (changed || this._vaoRecordInProgress) {
  13641. this.bindArrayBuffer(buffer);
  13642. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13643. }
  13644. };
  13645. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13646. if (indexBuffer == null) {
  13647. return;
  13648. }
  13649. if (this._cachedIndexBuffer !== indexBuffer) {
  13650. this._cachedIndexBuffer = indexBuffer;
  13651. this.bindIndexBuffer(indexBuffer);
  13652. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13653. }
  13654. };
  13655. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13656. var attributes = effect.getAttributesNames();
  13657. if (!this._vaoRecordInProgress) {
  13658. this._unbindVertexArrayObject();
  13659. }
  13660. this.unbindAllAttributes();
  13661. for (var index = 0; index < attributes.length; index++) {
  13662. var order = effect.getAttributeLocation(index);
  13663. if (order >= 0) {
  13664. var vertexBuffer = vertexBuffers[attributes[index]];
  13665. if (!vertexBuffer) {
  13666. continue;
  13667. }
  13668. this._gl.enableVertexAttribArray(order);
  13669. if (!this._vaoRecordInProgress) {
  13670. this._vertexAttribArraysEnabled[order] = true;
  13671. }
  13672. var buffer = vertexBuffer.getBuffer();
  13673. if (buffer) {
  13674. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13675. if (vertexBuffer.getIsInstanced()) {
  13676. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13677. if (!this._vaoRecordInProgress) {
  13678. this._currentInstanceLocations.push(order);
  13679. this._currentInstanceBuffers.push(buffer);
  13680. }
  13681. }
  13682. }
  13683. }
  13684. }
  13685. };
  13686. /**
  13687. * Records a vertex array object
  13688. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13689. * @param vertexBuffers defines the list of vertex buffers to store
  13690. * @param indexBuffer defines the index buffer to store
  13691. * @param effect defines the effect to store
  13692. * @returns the new vertex array object
  13693. */
  13694. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13695. var vao = this._gl.createVertexArray();
  13696. this._vaoRecordInProgress = true;
  13697. this._gl.bindVertexArray(vao);
  13698. this._mustWipeVertexAttributes = true;
  13699. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13700. this.bindIndexBuffer(indexBuffer);
  13701. this._vaoRecordInProgress = false;
  13702. this._gl.bindVertexArray(null);
  13703. return vao;
  13704. };
  13705. /**
  13706. * Bind a specific vertex array object
  13707. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13708. * @param vertexArrayObject defines the vertex array object to bind
  13709. * @param indexBuffer defines the index buffer to bind
  13710. */
  13711. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13712. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13713. this._cachedVertexArrayObject = vertexArrayObject;
  13714. this._gl.bindVertexArray(vertexArrayObject);
  13715. this._cachedVertexBuffers = null;
  13716. this._cachedIndexBuffer = null;
  13717. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13718. this._mustWipeVertexAttributes = true;
  13719. }
  13720. };
  13721. /**
  13722. * Bind webGl buffers directly to the webGL context
  13723. * @param vertexBuffer defines the vertex buffer to bind
  13724. * @param indexBuffer defines the index buffer to bind
  13725. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13726. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13727. * @param effect defines the effect associated with the vertex buffer
  13728. */
  13729. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13730. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13731. this._cachedVertexBuffers = vertexBuffer;
  13732. this._cachedEffectForVertexBuffers = effect;
  13733. var attributesCount = effect.getAttributesCount();
  13734. this._unbindVertexArrayObject();
  13735. this.unbindAllAttributes();
  13736. var offset = 0;
  13737. for (var index = 0; index < attributesCount; index++) {
  13738. if (index < vertexDeclaration.length) {
  13739. var order = effect.getAttributeLocation(index);
  13740. if (order >= 0) {
  13741. this._gl.enableVertexAttribArray(order);
  13742. this._vertexAttribArraysEnabled[order] = true;
  13743. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13744. }
  13745. offset += vertexDeclaration[index] * 4;
  13746. }
  13747. }
  13748. }
  13749. this._bindIndexBufferWithCache(indexBuffer);
  13750. };
  13751. Engine.prototype._unbindVertexArrayObject = function () {
  13752. if (!this._cachedVertexArrayObject) {
  13753. return;
  13754. }
  13755. this._cachedVertexArrayObject = null;
  13756. this._gl.bindVertexArray(null);
  13757. };
  13758. /**
  13759. * Bind a list of vertex buffers to the webGL context
  13760. * @param vertexBuffers defines the list of vertex buffers to bind
  13761. * @param indexBuffer defines the index buffer to bind
  13762. * @param effect defines the effect associated with the vertex buffers
  13763. */
  13764. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13765. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13766. this._cachedVertexBuffers = vertexBuffers;
  13767. this._cachedEffectForVertexBuffers = effect;
  13768. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13769. }
  13770. this._bindIndexBufferWithCache(indexBuffer);
  13771. };
  13772. /**
  13773. * Unbind all instance attributes
  13774. */
  13775. Engine.prototype.unbindInstanceAttributes = function () {
  13776. var boundBuffer;
  13777. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13778. var instancesBuffer = this._currentInstanceBuffers[i];
  13779. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13780. boundBuffer = instancesBuffer;
  13781. this.bindArrayBuffer(instancesBuffer);
  13782. }
  13783. var offsetLocation = this._currentInstanceLocations[i];
  13784. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13785. }
  13786. this._currentInstanceBuffers.length = 0;
  13787. this._currentInstanceLocations.length = 0;
  13788. };
  13789. /**
  13790. * Release and free the memory of a vertex array object
  13791. * @param vao defines the vertex array object to delete
  13792. */
  13793. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13794. this._gl.deleteVertexArray(vao);
  13795. };
  13796. /** @hidden */
  13797. Engine.prototype._releaseBuffer = function (buffer) {
  13798. buffer.references--;
  13799. if (buffer.references === 0) {
  13800. this._gl.deleteBuffer(buffer);
  13801. return true;
  13802. }
  13803. return false;
  13804. };
  13805. /**
  13806. * Creates a webGL buffer to use with instanciation
  13807. * @param capacity defines the size of the buffer
  13808. * @returns the webGL buffer
  13809. */
  13810. Engine.prototype.createInstancesBuffer = function (capacity) {
  13811. var buffer = this._gl.createBuffer();
  13812. if (!buffer) {
  13813. throw new Error("Unable to create instance buffer");
  13814. }
  13815. buffer.capacity = capacity;
  13816. this.bindArrayBuffer(buffer);
  13817. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13818. return buffer;
  13819. };
  13820. /**
  13821. * Delete a webGL buffer used with instanciation
  13822. * @param buffer defines the webGL buffer to delete
  13823. */
  13824. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13825. this._gl.deleteBuffer(buffer);
  13826. };
  13827. /**
  13828. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13829. * @param instancesBuffer defines the webGL buffer to update and bind
  13830. * @param data defines the data to store in the buffer
  13831. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13832. */
  13833. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13834. this.bindArrayBuffer(instancesBuffer);
  13835. if (data) {
  13836. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13837. }
  13838. if (offsetLocations[0].index !== undefined) {
  13839. var stride = 0;
  13840. for (var i = 0; i < offsetLocations.length; i++) {
  13841. var ai = offsetLocations[i];
  13842. stride += ai.attributeSize * 4;
  13843. }
  13844. for (var i = 0; i < offsetLocations.length; i++) {
  13845. var ai = offsetLocations[i];
  13846. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13847. this._gl.enableVertexAttribArray(ai.index);
  13848. this._vertexAttribArraysEnabled[ai.index] = true;
  13849. }
  13850. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13851. this._gl.vertexAttribDivisor(ai.index, 1);
  13852. this._currentInstanceLocations.push(ai.index);
  13853. this._currentInstanceBuffers.push(instancesBuffer);
  13854. }
  13855. }
  13856. else {
  13857. for (var index = 0; index < 4; index++) {
  13858. var offsetLocation = offsetLocations[index];
  13859. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13860. this._gl.enableVertexAttribArray(offsetLocation);
  13861. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13862. }
  13863. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13864. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13865. this._currentInstanceLocations.push(offsetLocation);
  13866. this._currentInstanceBuffers.push(instancesBuffer);
  13867. }
  13868. }
  13869. };
  13870. /**
  13871. * Apply all cached states (depth, culling, stencil and alpha)
  13872. */
  13873. Engine.prototype.applyStates = function () {
  13874. this._depthCullingState.apply(this._gl);
  13875. this._stencilState.apply(this._gl);
  13876. this._alphaState.apply(this._gl);
  13877. };
  13878. /**
  13879. * Send a draw order
  13880. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13881. * @param indexStart defines the starting index
  13882. * @param indexCount defines the number of index to draw
  13883. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13884. */
  13885. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13886. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13887. };
  13888. /**
  13889. * Draw a list of points
  13890. * @param verticesStart defines the index of first vertex to draw
  13891. * @param verticesCount defines the count of vertices to draw
  13892. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13893. */
  13894. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13895. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13896. };
  13897. /**
  13898. * Draw a list of unindexed primitives
  13899. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13900. * @param verticesStart defines the index of first vertex to draw
  13901. * @param verticesCount defines the count of vertices to draw
  13902. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13903. */
  13904. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13905. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13906. };
  13907. /**
  13908. * Draw a list of indexed primitives
  13909. * @param fillMode defines the primitive to use
  13910. * @param indexStart defines the starting index
  13911. * @param indexCount defines the number of index to draw
  13912. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13913. */
  13914. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13915. // Apply states
  13916. this.applyStates();
  13917. this._drawCalls.addCount(1, false);
  13918. // Render
  13919. var drawMode = this._drawMode(fillMode);
  13920. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13921. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13922. if (instancesCount) {
  13923. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13924. }
  13925. else {
  13926. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13927. }
  13928. };
  13929. /**
  13930. * Draw a list of unindexed primitives
  13931. * @param fillMode defines the primitive to use
  13932. * @param verticesStart defines the index of first vertex to draw
  13933. * @param verticesCount defines the count of vertices to draw
  13934. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13935. */
  13936. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13937. // Apply states
  13938. this.applyStates();
  13939. this._drawCalls.addCount(1, false);
  13940. var drawMode = this._drawMode(fillMode);
  13941. if (instancesCount) {
  13942. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13943. }
  13944. else {
  13945. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13946. }
  13947. };
  13948. Engine.prototype._drawMode = function (fillMode) {
  13949. switch (fillMode) {
  13950. // Triangle views
  13951. case BABYLON.Material.TriangleFillMode:
  13952. return this._gl.TRIANGLES;
  13953. case BABYLON.Material.PointFillMode:
  13954. return this._gl.POINTS;
  13955. case BABYLON.Material.WireFrameFillMode:
  13956. return this._gl.LINES;
  13957. // Draw modes
  13958. case BABYLON.Material.PointListDrawMode:
  13959. return this._gl.POINTS;
  13960. case BABYLON.Material.LineListDrawMode:
  13961. return this._gl.LINES;
  13962. case BABYLON.Material.LineLoopDrawMode:
  13963. return this._gl.LINE_LOOP;
  13964. case BABYLON.Material.LineStripDrawMode:
  13965. return this._gl.LINE_STRIP;
  13966. case BABYLON.Material.TriangleStripDrawMode:
  13967. return this._gl.TRIANGLE_STRIP;
  13968. case BABYLON.Material.TriangleFanDrawMode:
  13969. return this._gl.TRIANGLE_FAN;
  13970. default:
  13971. return this._gl.TRIANGLES;
  13972. }
  13973. };
  13974. // Shaders
  13975. /** @hidden */
  13976. Engine.prototype._releaseEffect = function (effect) {
  13977. if (this._compiledEffects[effect._key]) {
  13978. delete this._compiledEffects[effect._key];
  13979. this._deleteProgram(effect.getProgram());
  13980. }
  13981. };
  13982. /** @hidden */
  13983. Engine.prototype._deleteProgram = function (program) {
  13984. if (program) {
  13985. program.__SPECTOR_rebuildProgram = null;
  13986. if (program.transformFeedback) {
  13987. this.deleteTransformFeedback(program.transformFeedback);
  13988. program.transformFeedback = null;
  13989. }
  13990. this._gl.deleteProgram(program);
  13991. }
  13992. };
  13993. /**
  13994. * Create a new effect (used to store vertex/fragment shaders)
  13995. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13996. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13997. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13998. * @param samplers defines an array of string used to represent textures
  13999. * @param defines defines the string containing the defines to use to compile the shaders
  14000. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14001. * @param onCompiled defines a function to call when the effect creation is successful
  14002. * @param onError defines a function to call when the effect creation has failed
  14003. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14004. * @returns the new Effect
  14005. */
  14006. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14007. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14008. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14009. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14010. if (this._compiledEffects[name]) {
  14011. var compiledEffect = this._compiledEffects[name];
  14012. if (onCompiled && compiledEffect.isReady()) {
  14013. onCompiled(compiledEffect);
  14014. }
  14015. return compiledEffect;
  14016. }
  14017. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14018. effect._key = name;
  14019. this._compiledEffects[name] = effect;
  14020. return effect;
  14021. };
  14022. /**
  14023. * Create an effect to use with particle systems.
  14024. * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration
  14025. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14026. * @param uniformsNames defines a list of attribute names
  14027. * @param samplers defines an array of string used to represent textures
  14028. * @param defines defines the string containing the defines to use to compile the shaders
  14029. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14030. * @param onCompiled defines a function to call when the effect creation is successful
  14031. * @param onError defines a function to call when the effect creation has failed
  14032. * @returns the new Effect
  14033. */
  14034. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14035. if (uniformsNames === void 0) { uniformsNames = []; }
  14036. if (samplers === void 0) { samplers = []; }
  14037. if (defines === void 0) { defines = ""; }
  14038. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  14039. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  14040. if (defines.indexOf(" BILLBOARD") === -1) {
  14041. defines += "\n#define BILLBOARD\n";
  14042. }
  14043. if (samplers.indexOf("diffuseSampler") === -1) {
  14044. samplers.push("diffuseSampler");
  14045. }
  14046. return this.createEffect({
  14047. vertex: "particles",
  14048. fragmentElement: fragmentName
  14049. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  14050. };
  14051. /**
  14052. * Directly creates a webGL program
  14053. * @param vertexCode defines the vertex shader code to use
  14054. * @param fragmentCode defines the fragment shader code to use
  14055. * @param context defines the webGL context to use (if not set, the current one will be used)
  14056. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14057. * @returns the new webGL program
  14058. */
  14059. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14060. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14061. context = context || this._gl;
  14062. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14063. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14064. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14065. };
  14066. /**
  14067. * Creates a webGL program
  14068. * @param vertexCode defines the vertex shader code to use
  14069. * @param fragmentCode defines the fragment shader code to use
  14070. * @param defines defines the string containing the defines to use to compile the shaders
  14071. * @param context defines the webGL context to use (if not set, the current one will be used)
  14072. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14073. * @returns the new webGL program
  14074. */
  14075. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14076. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14077. context = context || this._gl;
  14078. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14079. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14080. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14081. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14082. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14083. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14084. return program;
  14085. };
  14086. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14087. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14088. var shaderProgram = context.createProgram();
  14089. if (!shaderProgram) {
  14090. throw new Error("Unable to create program");
  14091. }
  14092. context.attachShader(shaderProgram, vertexShader);
  14093. context.attachShader(shaderProgram, fragmentShader);
  14094. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14095. var transformFeedback = this.createTransformFeedback();
  14096. this.bindTransformFeedback(transformFeedback);
  14097. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14098. shaderProgram.transformFeedback = transformFeedback;
  14099. }
  14100. context.linkProgram(shaderProgram);
  14101. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14102. this.bindTransformFeedback(null);
  14103. }
  14104. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14105. if (!linked) {
  14106. var error = context.getProgramInfoLog(shaderProgram);
  14107. if (error) {
  14108. throw new Error(error);
  14109. }
  14110. }
  14111. context.validateProgram(shaderProgram);
  14112. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14113. if (!validated) {
  14114. var error = context.getProgramInfoLog(shaderProgram);
  14115. if (error) {
  14116. throw new Error(error);
  14117. }
  14118. }
  14119. context.deleteShader(vertexShader);
  14120. context.deleteShader(fragmentShader);
  14121. return shaderProgram;
  14122. };
  14123. /**
  14124. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14125. * @param shaderProgram defines the webGL program to use
  14126. * @param uniformsNames defines the list of uniform names
  14127. * @returns an array of webGL uniform locations
  14128. */
  14129. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14130. var results = new Array();
  14131. for (var index = 0; index < uniformsNames.length; index++) {
  14132. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14133. }
  14134. return results;
  14135. };
  14136. /**
  14137. * Gets the lsit of active attributes for a given webGL program
  14138. * @param shaderProgram defines the webGL program to use
  14139. * @param attributesNames defines the list of attribute names to get
  14140. * @returns an array of indices indicating the offset of each attribute
  14141. */
  14142. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14143. var results = [];
  14144. for (var index = 0; index < attributesNames.length; index++) {
  14145. try {
  14146. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14147. }
  14148. catch (e) {
  14149. results.push(-1);
  14150. }
  14151. }
  14152. return results;
  14153. };
  14154. /**
  14155. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14156. * @param effect defines the effect to activate
  14157. */
  14158. Engine.prototype.enableEffect = function (effect) {
  14159. if (!effect) {
  14160. return;
  14161. }
  14162. // Use program
  14163. this.bindSamplers(effect);
  14164. this._currentEffect = effect;
  14165. if (effect.onBind) {
  14166. effect.onBind(effect);
  14167. }
  14168. effect.onBindObservable.notifyObservers(effect);
  14169. };
  14170. /**
  14171. * Set the value of an uniform to an array of int32
  14172. * @param uniform defines the webGL uniform location where to store the value
  14173. * @param array defines the array of int32 to store
  14174. */
  14175. Engine.prototype.setIntArray = function (uniform, array) {
  14176. if (!uniform)
  14177. return;
  14178. this._gl.uniform1iv(uniform, array);
  14179. };
  14180. /**
  14181. * Set the value of an uniform to an array of int32 (stored as vec2)
  14182. * @param uniform defines the webGL uniform location where to store the value
  14183. * @param array defines the array of int32 to store
  14184. */
  14185. Engine.prototype.setIntArray2 = function (uniform, array) {
  14186. if (!uniform || array.length % 2 !== 0)
  14187. return;
  14188. this._gl.uniform2iv(uniform, array);
  14189. };
  14190. /**
  14191. * Set the value of an uniform to an array of int32 (stored as vec3)
  14192. * @param uniform defines the webGL uniform location where to store the value
  14193. * @param array defines the array of int32 to store
  14194. */
  14195. Engine.prototype.setIntArray3 = function (uniform, array) {
  14196. if (!uniform || array.length % 3 !== 0)
  14197. return;
  14198. this._gl.uniform3iv(uniform, array);
  14199. };
  14200. /**
  14201. * Set the value of an uniform to an array of int32 (stored as vec4)
  14202. * @param uniform defines the webGL uniform location where to store the value
  14203. * @param array defines the array of int32 to store
  14204. */
  14205. Engine.prototype.setIntArray4 = function (uniform, array) {
  14206. if (!uniform || array.length % 4 !== 0)
  14207. return;
  14208. this._gl.uniform4iv(uniform, array);
  14209. };
  14210. /**
  14211. * Set the value of an uniform to an array of float32
  14212. * @param uniform defines the webGL uniform location where to store the value
  14213. * @param array defines the array of float32 to store
  14214. */
  14215. Engine.prototype.setFloatArray = function (uniform, array) {
  14216. if (!uniform)
  14217. return;
  14218. this._gl.uniform1fv(uniform, array);
  14219. };
  14220. /**
  14221. * Set the value of an uniform to an array of float32 (stored as vec2)
  14222. * @param uniform defines the webGL uniform location where to store the value
  14223. * @param array defines the array of float32 to store
  14224. */
  14225. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14226. if (!uniform || array.length % 2 !== 0)
  14227. return;
  14228. this._gl.uniform2fv(uniform, array);
  14229. };
  14230. /**
  14231. * Set the value of an uniform to an array of float32 (stored as vec3)
  14232. * @param uniform defines the webGL uniform location where to store the value
  14233. * @param array defines the array of float32 to store
  14234. */
  14235. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14236. if (!uniform || array.length % 3 !== 0)
  14237. return;
  14238. this._gl.uniform3fv(uniform, array);
  14239. };
  14240. /**
  14241. * Set the value of an uniform to an array of float32 (stored as vec4)
  14242. * @param uniform defines the webGL uniform location where to store the value
  14243. * @param array defines the array of float32 to store
  14244. */
  14245. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14246. if (!uniform || array.length % 4 !== 0)
  14247. return;
  14248. this._gl.uniform4fv(uniform, array);
  14249. };
  14250. /**
  14251. * Set the value of an uniform to an array of number
  14252. * @param uniform defines the webGL uniform location where to store the value
  14253. * @param array defines the array of number to store
  14254. */
  14255. Engine.prototype.setArray = function (uniform, array) {
  14256. if (!uniform)
  14257. return;
  14258. this._gl.uniform1fv(uniform, array);
  14259. };
  14260. /**
  14261. * Set the value of an uniform to an array of number (stored as vec2)
  14262. * @param uniform defines the webGL uniform location where to store the value
  14263. * @param array defines the array of number to store
  14264. */
  14265. Engine.prototype.setArray2 = function (uniform, array) {
  14266. if (!uniform || array.length % 2 !== 0)
  14267. return;
  14268. this._gl.uniform2fv(uniform, array);
  14269. };
  14270. /**
  14271. * Set the value of an uniform to an array of number (stored as vec3)
  14272. * @param uniform defines the webGL uniform location where to store the value
  14273. * @param array defines the array of number to store
  14274. */
  14275. Engine.prototype.setArray3 = function (uniform, array) {
  14276. if (!uniform || array.length % 3 !== 0)
  14277. return;
  14278. this._gl.uniform3fv(uniform, array);
  14279. };
  14280. /**
  14281. * Set the value of an uniform to an array of number (stored as vec4)
  14282. * @param uniform defines the webGL uniform location where to store the value
  14283. * @param array defines the array of number to store
  14284. */
  14285. Engine.prototype.setArray4 = function (uniform, array) {
  14286. if (!uniform || array.length % 4 !== 0)
  14287. return;
  14288. this._gl.uniform4fv(uniform, array);
  14289. };
  14290. /**
  14291. * Set the value of an uniform to an array of float32 (stored as matrices)
  14292. * @param uniform defines the webGL uniform location where to store the value
  14293. * @param matrices defines the array of float32 to store
  14294. */
  14295. Engine.prototype.setMatrices = function (uniform, matrices) {
  14296. if (!uniform)
  14297. return;
  14298. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14299. };
  14300. /**
  14301. * Set the value of an uniform to a matrix
  14302. * @param uniform defines the webGL uniform location where to store the value
  14303. * @param matrix defines the matrix to store
  14304. */
  14305. Engine.prototype.setMatrix = function (uniform, matrix) {
  14306. if (!uniform)
  14307. return;
  14308. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14309. };
  14310. /**
  14311. * Set the value of an uniform to a matrix (3x3)
  14312. * @param uniform defines the webGL uniform location where to store the value
  14313. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14314. */
  14315. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14316. if (!uniform)
  14317. return;
  14318. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14319. };
  14320. /**
  14321. * Set the value of an uniform to a matrix (2x2)
  14322. * @param uniform defines the webGL uniform location where to store the value
  14323. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14324. */
  14325. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14326. if (!uniform)
  14327. return;
  14328. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14329. };
  14330. /**
  14331. * Set the value of an uniform to a number (int)
  14332. * @param uniform defines the webGL uniform location where to store the value
  14333. * @param value defines the int number to store
  14334. */
  14335. Engine.prototype.setInt = function (uniform, value) {
  14336. if (!uniform)
  14337. return;
  14338. this._gl.uniform1i(uniform, value);
  14339. };
  14340. /**
  14341. * Set the value of an uniform to a number (float)
  14342. * @param uniform defines the webGL uniform location where to store the value
  14343. * @param value defines the float number to store
  14344. */
  14345. Engine.prototype.setFloat = function (uniform, value) {
  14346. if (!uniform)
  14347. return;
  14348. this._gl.uniform1f(uniform, value);
  14349. };
  14350. /**
  14351. * Set the value of an uniform to a vec2
  14352. * @param uniform defines the webGL uniform location where to store the value
  14353. * @param x defines the 1st component of the value
  14354. * @param y defines the 2nd component of the value
  14355. */
  14356. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14357. if (!uniform)
  14358. return;
  14359. this._gl.uniform2f(uniform, x, y);
  14360. };
  14361. /**
  14362. * Set the value of an uniform to a vec3
  14363. * @param uniform defines the webGL uniform location where to store the value
  14364. * @param x defines the 1st component of the value
  14365. * @param y defines the 2nd component of the value
  14366. * @param z defines the 3rd component of the value
  14367. */
  14368. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14369. if (!uniform)
  14370. return;
  14371. this._gl.uniform3f(uniform, x, y, z);
  14372. };
  14373. /**
  14374. * Set the value of an uniform to a boolean
  14375. * @param uniform defines the webGL uniform location where to store the value
  14376. * @param bool defines the boolean to store
  14377. */
  14378. Engine.prototype.setBool = function (uniform, bool) {
  14379. if (!uniform)
  14380. return;
  14381. this._gl.uniform1i(uniform, bool);
  14382. };
  14383. /**
  14384. * Set the value of an uniform to a vec4
  14385. * @param uniform defines the webGL uniform location where to store the value
  14386. * @param x defines the 1st component of the value
  14387. * @param y defines the 2nd component of the value
  14388. * @param z defines the 3rd component of the value
  14389. * @param w defines the 4th component of the value
  14390. */
  14391. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14392. if (!uniform)
  14393. return;
  14394. this._gl.uniform4f(uniform, x, y, z, w);
  14395. };
  14396. /**
  14397. * Set the value of an uniform to a Color3
  14398. * @param uniform defines the webGL uniform location where to store the value
  14399. * @param color3 defines the color to store
  14400. */
  14401. Engine.prototype.setColor3 = function (uniform, color3) {
  14402. if (!uniform)
  14403. return;
  14404. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14405. };
  14406. /**
  14407. * Set the value of an uniform to a Color3 and an alpha value
  14408. * @param uniform defines the webGL uniform location where to store the value
  14409. * @param color3 defines the color to store
  14410. * @param alpha defines the alpha component to store
  14411. */
  14412. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14413. if (!uniform)
  14414. return;
  14415. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14416. };
  14417. /**
  14418. * Sets a Color4 on a uniform variable
  14419. * @param uniform defines the uniform location
  14420. * @param color4 defines the value to be set
  14421. */
  14422. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14423. if (!uniform)
  14424. return;
  14425. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14426. };
  14427. // States
  14428. /**
  14429. * Set various states to the webGL context
  14430. * @param culling defines backface culling state
  14431. * @param zOffset defines the value to apply to zOffset (0 by default)
  14432. * @param force defines if states must be applied even if cache is up to date
  14433. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14434. */
  14435. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14436. if (zOffset === void 0) { zOffset = 0; }
  14437. if (reverseSide === void 0) { reverseSide = false; }
  14438. // Culling
  14439. if (this._depthCullingState.cull !== culling || force) {
  14440. this._depthCullingState.cull = culling;
  14441. }
  14442. // Cull face
  14443. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14444. if (this._depthCullingState.cullFace !== cullFace || force) {
  14445. this._depthCullingState.cullFace = cullFace;
  14446. }
  14447. // Z offset
  14448. this.setZOffset(zOffset);
  14449. // Front face
  14450. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14451. if (this._depthCullingState.frontFace !== frontFace || force) {
  14452. this._depthCullingState.frontFace = frontFace;
  14453. }
  14454. };
  14455. /**
  14456. * Set the z offset to apply to current rendering
  14457. * @param value defines the offset to apply
  14458. */
  14459. Engine.prototype.setZOffset = function (value) {
  14460. this._depthCullingState.zOffset = value;
  14461. };
  14462. /**
  14463. * Gets the current value of the zOffset
  14464. * @returns the current zOffset state
  14465. */
  14466. Engine.prototype.getZOffset = function () {
  14467. return this._depthCullingState.zOffset;
  14468. };
  14469. /**
  14470. * Enable or disable depth buffering
  14471. * @param enable defines the state to set
  14472. */
  14473. Engine.prototype.setDepthBuffer = function (enable) {
  14474. this._depthCullingState.depthTest = enable;
  14475. };
  14476. /**
  14477. * Gets a boolean indicating if depth writing is enabled
  14478. * @returns the current depth writing state
  14479. */
  14480. Engine.prototype.getDepthWrite = function () {
  14481. return this._depthCullingState.depthMask;
  14482. };
  14483. /**
  14484. * Enable or disable depth writing
  14485. * @param enable defines the state to set
  14486. */
  14487. Engine.prototype.setDepthWrite = function (enable) {
  14488. this._depthCullingState.depthMask = enable;
  14489. };
  14490. /**
  14491. * Enable or disable color writing
  14492. * @param enable defines the state to set
  14493. */
  14494. Engine.prototype.setColorWrite = function (enable) {
  14495. this._gl.colorMask(enable, enable, enable, enable);
  14496. this._colorWrite = enable;
  14497. };
  14498. /**
  14499. * Gets a boolean indicating if color writing is enabled
  14500. * @returns the current color writing state
  14501. */
  14502. Engine.prototype.getColorWrite = function () {
  14503. return this._colorWrite;
  14504. };
  14505. /**
  14506. * Sets alpha constants used by some alpha blending modes
  14507. * @param r defines the red component
  14508. * @param g defines the green component
  14509. * @param b defines the blue component
  14510. * @param a defines the alpha component
  14511. */
  14512. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14513. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14514. };
  14515. /**
  14516. * Sets the current alpha mode
  14517. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14518. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14519. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14520. */
  14521. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14522. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14523. if (this._alphaMode === mode) {
  14524. return;
  14525. }
  14526. switch (mode) {
  14527. case Engine.ALPHA_DISABLE:
  14528. this._alphaState.alphaBlend = false;
  14529. break;
  14530. case Engine.ALPHA_PREMULTIPLIED:
  14531. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14532. this._alphaState.alphaBlend = true;
  14533. break;
  14534. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14535. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14536. this._alphaState.alphaBlend = true;
  14537. break;
  14538. case Engine.ALPHA_COMBINE:
  14539. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14540. this._alphaState.alphaBlend = true;
  14541. break;
  14542. case Engine.ALPHA_ONEONE:
  14543. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14544. this._alphaState.alphaBlend = true;
  14545. break;
  14546. case Engine.ALPHA_ADD:
  14547. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14548. this._alphaState.alphaBlend = true;
  14549. break;
  14550. case Engine.ALPHA_SUBTRACT:
  14551. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14552. this._alphaState.alphaBlend = true;
  14553. break;
  14554. case Engine.ALPHA_MULTIPLY:
  14555. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14556. this._alphaState.alphaBlend = true;
  14557. break;
  14558. case Engine.ALPHA_MAXIMIZED:
  14559. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14560. this._alphaState.alphaBlend = true;
  14561. break;
  14562. case Engine.ALPHA_INTERPOLATE:
  14563. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14564. this._alphaState.alphaBlend = true;
  14565. break;
  14566. case Engine.ALPHA_SCREENMODE:
  14567. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14568. this._alphaState.alphaBlend = true;
  14569. break;
  14570. }
  14571. if (!noDepthWriteChange) {
  14572. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14573. }
  14574. this._alphaMode = mode;
  14575. };
  14576. /**
  14577. * Gets the current alpha mode
  14578. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14579. * @returns the current alpha mode
  14580. */
  14581. Engine.prototype.getAlphaMode = function () {
  14582. return this._alphaMode;
  14583. };
  14584. // Textures
  14585. /**
  14586. * Clears the list of texture accessible through engine.
  14587. * This can help preventing texture load conflict due to name collision.
  14588. */
  14589. Engine.prototype.clearInternalTexturesCache = function () {
  14590. this._internalTexturesCache = [];
  14591. };
  14592. /**
  14593. * Force the entire cache to be cleared
  14594. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14595. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14596. */
  14597. Engine.prototype.wipeCaches = function (bruteForce) {
  14598. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14599. return;
  14600. }
  14601. this._currentEffect = null;
  14602. this._unpackFlipYCached = null;
  14603. this._viewportCached.x = 0;
  14604. this._viewportCached.y = 0;
  14605. this._viewportCached.z = 0;
  14606. this._viewportCached.w = 0;
  14607. if (bruteForce) {
  14608. this.resetTextureCache();
  14609. this._currentProgram = null;
  14610. this._stencilState.reset();
  14611. this._depthCullingState.reset();
  14612. this.setDepthFunctionToLessOrEqual();
  14613. this._alphaState.reset();
  14614. }
  14615. this._resetVertexBufferBinding();
  14616. this._cachedIndexBuffer = null;
  14617. this._cachedEffectForVertexBuffers = null;
  14618. this._unbindVertexArrayObject();
  14619. this.bindIndexBuffer(null);
  14620. };
  14621. /**
  14622. * Set the compressed texture format to use, based on the formats you have, and the formats
  14623. * supported by the hardware / browser.
  14624. *
  14625. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14626. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14627. * to API arguments needed to compressed textures. This puts the burden on the container
  14628. * generator to house the arcane code for determining these for current & future formats.
  14629. *
  14630. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14631. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14632. *
  14633. * Note: The result of this call is not taken into account when a texture is base64.
  14634. *
  14635. * @param formatsAvailable defines the list of those format families you have created
  14636. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14637. *
  14638. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14639. * @returns The extension selected.
  14640. */
  14641. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14642. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14643. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14644. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14645. return this._textureFormatInUse = this._texturesSupported[i];
  14646. }
  14647. }
  14648. }
  14649. // actively set format to nothing, to allow this to be called more than once
  14650. // and possibly fail the 2nd time
  14651. this._textureFormatInUse = null;
  14652. return null;
  14653. };
  14654. /** @hidden */
  14655. Engine.prototype._createTexture = function () {
  14656. var texture = this._gl.createTexture();
  14657. if (!texture) {
  14658. throw new Error("Unable to create texture");
  14659. }
  14660. return texture;
  14661. };
  14662. /**
  14663. * Usually called from BABYLON.Texture.ts.
  14664. * Passed information to create a WebGLTexture
  14665. * @param urlArg defines a value which contains one of the following:
  14666. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14667. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14668. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14669. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14670. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14671. * @param scene needed for loading to the correct scene
  14672. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14673. * @param onLoad optional callback to be called upon successful completion
  14674. * @param onError optional callback to be called upon failure
  14675. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14676. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14677. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14678. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14679. */
  14680. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14681. var _this = this;
  14682. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14683. if (onLoad === void 0) { onLoad = null; }
  14684. if (onError === void 0) { onError = null; }
  14685. if (buffer === void 0) { buffer = null; }
  14686. if (fallback === void 0) { fallback = null; }
  14687. if (format === void 0) { format = null; }
  14688. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14689. var fromData = url.substr(0, 5) === "data:";
  14690. var fromBlob = url.substr(0, 5) === "blob:";
  14691. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14692. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14693. // establish the file extension, if possible
  14694. var lastDot = url.lastIndexOf('.');
  14695. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14696. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14697. var isTGA = (extension.indexOf(".tga") === 0);
  14698. // determine if a ktx file should be substituted
  14699. var isKTX = false;
  14700. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14701. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14702. isKTX = true;
  14703. }
  14704. if (scene) {
  14705. scene._addPendingData(texture);
  14706. }
  14707. texture.url = url;
  14708. texture.generateMipMaps = !noMipmap;
  14709. texture.samplingMode = samplingMode;
  14710. texture.invertY = invertY;
  14711. if (!this._doNotHandleContextLost) {
  14712. // Keep a link to the buffer only if we plan to handle context lost
  14713. texture._buffer = buffer;
  14714. }
  14715. var onLoadObserver = null;
  14716. if (onLoad && !fallback) {
  14717. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14718. }
  14719. if (!fallback)
  14720. this._internalTexturesCache.push(texture);
  14721. var onerror = function (message, exception) {
  14722. if (scene) {
  14723. scene._removePendingData(texture);
  14724. }
  14725. if (onLoadObserver && !isKTX) {
  14726. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14727. texture.onLoadedObservable.remove(onLoadObserver);
  14728. }
  14729. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14730. if (isKTX) {
  14731. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14732. }
  14733. else if (BABYLON.Tools.UseFallbackTexture) {
  14734. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14735. }
  14736. if (onError) {
  14737. onError(message || "Unknown error", exception);
  14738. }
  14739. };
  14740. var callback = null;
  14741. // processing for non-image formats
  14742. if (isKTX || isTGA || isDDS) {
  14743. if (isKTX) {
  14744. callback = function (data) {
  14745. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14746. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14747. ktx.uploadLevels(_this._gl, !noMipmap);
  14748. return false;
  14749. }, samplingMode);
  14750. };
  14751. }
  14752. else if (isTGA) {
  14753. callback = function (arrayBuffer) {
  14754. var data = new Uint8Array(arrayBuffer);
  14755. var header = BABYLON.TGATools.GetTGAHeader(data);
  14756. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14757. BABYLON.TGATools.UploadContent(_this._gl, data);
  14758. return false;
  14759. }, samplingMode);
  14760. };
  14761. }
  14762. else if (isDDS) {
  14763. callback = function (data) {
  14764. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14765. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14766. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14767. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14768. return false;
  14769. }, samplingMode);
  14770. };
  14771. }
  14772. if (!buffer) {
  14773. this._loadFile(url, function (data) {
  14774. if (callback) {
  14775. callback(data);
  14776. }
  14777. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14778. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14779. });
  14780. }
  14781. else {
  14782. if (callback) {
  14783. callback(buffer);
  14784. }
  14785. }
  14786. // image format processing
  14787. }
  14788. else {
  14789. var onload = function (img) {
  14790. if (fromBlob && !_this._doNotHandleContextLost) {
  14791. // We need to store the image if we need to rebuild the texture
  14792. // in case of a webgl context lost
  14793. texture._buffer = img;
  14794. }
  14795. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14796. var gl = _this._gl;
  14797. var isPot = (img.width === potWidth && img.height === potHeight);
  14798. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14799. if (isPot) {
  14800. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14801. return false;
  14802. }
  14803. var maxTextureSize = _this._caps.maxTextureSize;
  14804. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14805. _this._prepareWorkingCanvas();
  14806. if (!_this._workingCanvas || !_this._workingContext) {
  14807. return false;
  14808. }
  14809. _this._workingCanvas.width = potWidth;
  14810. _this._workingCanvas.height = potHeight;
  14811. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14812. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14813. texture.width = potWidth;
  14814. texture.height = potHeight;
  14815. return false;
  14816. }
  14817. else {
  14818. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14819. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14820. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14821. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14822. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14823. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14824. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14825. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14826. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14827. _this._releaseTexture(source_1);
  14828. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14829. continuationCallback();
  14830. });
  14831. }
  14832. return true;
  14833. }, samplingMode);
  14834. };
  14835. if (!fromData || isBase64) {
  14836. if (buffer instanceof HTMLImageElement) {
  14837. onload(buffer);
  14838. }
  14839. else {
  14840. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14841. }
  14842. }
  14843. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14844. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14845. }
  14846. else {
  14847. onload(buffer);
  14848. }
  14849. }
  14850. return texture;
  14851. };
  14852. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14853. var _this = this;
  14854. var rtt = this.createRenderTargetTexture({
  14855. width: destination.width,
  14856. height: destination.height,
  14857. }, {
  14858. generateMipMaps: false,
  14859. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14860. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14861. generateDepthBuffer: false,
  14862. generateStencilBuffer: false
  14863. });
  14864. if (!this._rescalePostProcess) {
  14865. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14866. }
  14867. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14868. _this._rescalePostProcess.onApply = function (effect) {
  14869. effect._bindTexture("textureSampler", source);
  14870. };
  14871. var hostingScene = scene;
  14872. if (!hostingScene) {
  14873. hostingScene = _this.scenes[_this.scenes.length - 1];
  14874. }
  14875. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14876. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14877. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14878. _this.unBindFramebuffer(rtt);
  14879. _this._releaseTexture(rtt);
  14880. if (onComplete) {
  14881. onComplete();
  14882. }
  14883. });
  14884. };
  14885. /**
  14886. * Update a raw texture
  14887. * @param texture defines the texture to update
  14888. * @param data defines the data to store in the texture
  14889. * @param format defines the format of the data
  14890. * @param invertY defines if data must be stored with Y axis inverted
  14891. * @param compression defines the compression used (null by default)
  14892. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14893. */
  14894. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14895. if (compression === void 0) { compression = null; }
  14896. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14897. if (!texture) {
  14898. return;
  14899. }
  14900. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14901. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14902. // babylon's internalFormat but gl's texImage2D format
  14903. var internalFormat = this._getInternalFormat(format);
  14904. var textureType = this._getWebGLTextureType(type);
  14905. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14906. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14907. if (!this._doNotHandleContextLost) {
  14908. texture._bufferView = data;
  14909. texture.format = format;
  14910. texture.type = type;
  14911. texture.invertY = invertY;
  14912. texture._compression = compression;
  14913. }
  14914. if (texture.width % 4 !== 0) {
  14915. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14916. }
  14917. if (compression && data) {
  14918. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14919. }
  14920. else {
  14921. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14922. }
  14923. if (texture.generateMipMaps) {
  14924. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14925. }
  14926. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14927. // this.resetTextureCache();
  14928. texture.isReady = true;
  14929. };
  14930. /**
  14931. * Creates a raw texture
  14932. * @param data defines the data to store in the texture
  14933. * @param width defines the width of the texture
  14934. * @param height defines the height of the texture
  14935. * @param format defines the format of the data
  14936. * @param generateMipMaps defines if the engine should generate the mip levels
  14937. * @param invertY defines if data must be stored with Y axis inverted
  14938. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14939. * @param compression defines the compression used (null by default)
  14940. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14941. * @returns the raw texture inside an InternalTexture
  14942. */
  14943. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14944. if (compression === void 0) { compression = null; }
  14945. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14946. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14947. texture.baseWidth = width;
  14948. texture.baseHeight = height;
  14949. texture.width = width;
  14950. texture.height = height;
  14951. texture.format = format;
  14952. texture.generateMipMaps = generateMipMaps;
  14953. texture.samplingMode = samplingMode;
  14954. texture.invertY = invertY;
  14955. texture._compression = compression;
  14956. texture.type = type;
  14957. if (!this._doNotHandleContextLost) {
  14958. texture._bufferView = data;
  14959. }
  14960. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14961. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14962. // Filters
  14963. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14964. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14965. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14966. if (generateMipMaps) {
  14967. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14968. }
  14969. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14970. this._internalTexturesCache.push(texture);
  14971. return texture;
  14972. };
  14973. /** @hidden */
  14974. Engine.prototype._unpackFlipY = function (value) {
  14975. if (this._unpackFlipYCached !== value) {
  14976. this._unpackFlipYCached = value;
  14977. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14978. }
  14979. };
  14980. /**
  14981. * Creates a dynamic texture
  14982. * @param width defines the width of the texture
  14983. * @param height defines the height of the texture
  14984. * @param generateMipMaps defines if the engine should generate the mip levels
  14985. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14986. * @returns the dynamic texture inside an InternalTexture
  14987. */
  14988. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14989. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14990. texture.baseWidth = width;
  14991. texture.baseHeight = height;
  14992. if (generateMipMaps) {
  14993. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14994. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14995. }
  14996. // this.resetTextureCache();
  14997. texture.width = width;
  14998. texture.height = height;
  14999. texture.isReady = false;
  15000. texture.generateMipMaps = generateMipMaps;
  15001. texture.samplingMode = samplingMode;
  15002. this.updateTextureSamplingMode(samplingMode, texture);
  15003. this._internalTexturesCache.push(texture);
  15004. return texture;
  15005. };
  15006. /**
  15007. * Update the sampling mode of a given texture
  15008. * @param samplingMode defines the required sampling mode
  15009. * @param texture defines the texture to update
  15010. */
  15011. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15012. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  15013. if (texture.isCube) {
  15014. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15015. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15016. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15017. }
  15018. else if (texture.is3D) {
  15019. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15020. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15021. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15022. }
  15023. else {
  15024. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15025. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15026. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15027. }
  15028. texture.samplingMode = samplingMode;
  15029. };
  15030. /**
  15031. * Update the content of a dynamic texture
  15032. * @param texture defines the texture to update
  15033. * @param canvas defines the canvas containing the source
  15034. * @param invertY defines if data must be stored with Y axis inverted
  15035. * @param premulAlpha defines if alpha is stored as premultiplied
  15036. * @param format defines the format of the data
  15037. */
  15038. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15039. if (premulAlpha === void 0) { premulAlpha = false; }
  15040. if (!texture) {
  15041. return;
  15042. }
  15043. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15044. this._unpackFlipY(invertY);
  15045. if (premulAlpha) {
  15046. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15047. }
  15048. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15049. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15050. if (texture.generateMipMaps) {
  15051. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15052. }
  15053. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15054. if (premulAlpha) {
  15055. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15056. }
  15057. texture.isReady = true;
  15058. };
  15059. /**
  15060. * Update a video texture
  15061. * @param texture defines the texture to update
  15062. * @param video defines the video element to use
  15063. * @param invertY defines if data must be stored with Y axis inverted
  15064. */
  15065. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15066. if (!texture || texture._isDisabled) {
  15067. return;
  15068. }
  15069. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15070. this._unpackFlipY(!invertY); // Video are upside down by default
  15071. try {
  15072. // Testing video texture support
  15073. if (this._videoTextureSupported === undefined) {
  15074. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15075. if (this._gl.getError() !== 0) {
  15076. this._videoTextureSupported = false;
  15077. }
  15078. else {
  15079. this._videoTextureSupported = true;
  15080. }
  15081. }
  15082. // Copy video through the current working canvas if video texture is not supported
  15083. if (!this._videoTextureSupported) {
  15084. if (!texture._workingCanvas) {
  15085. texture._workingCanvas = document.createElement("canvas");
  15086. var context = texture._workingCanvas.getContext("2d");
  15087. if (!context) {
  15088. throw new Error("Unable to get 2d context");
  15089. }
  15090. texture._workingContext = context;
  15091. texture._workingCanvas.width = texture.width;
  15092. texture._workingCanvas.height = texture.height;
  15093. }
  15094. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15095. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15096. }
  15097. else {
  15098. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15099. }
  15100. if (texture.generateMipMaps) {
  15101. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15102. }
  15103. if (!wasPreviouslyBound) {
  15104. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15105. }
  15106. // this.resetTextureCache();
  15107. texture.isReady = true;
  15108. }
  15109. catch (ex) {
  15110. // Something unexpected
  15111. // Let's disable the texture
  15112. texture._isDisabled = true;
  15113. }
  15114. };
  15115. /**
  15116. * Updates a depth texture Comparison Mode and Function.
  15117. * If the comparison Function is equal to 0, the mode will be set to none.
  15118. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15119. * @param texture The texture to set the comparison function for
  15120. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15121. */
  15122. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15123. if (this.webGLVersion === 1) {
  15124. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15125. return;
  15126. }
  15127. var gl = this._gl;
  15128. if (texture.isCube) {
  15129. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15130. if (comparisonFunction === 0) {
  15131. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15132. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15133. }
  15134. else {
  15135. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15136. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15137. }
  15138. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15139. }
  15140. else {
  15141. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15142. if (comparisonFunction === 0) {
  15143. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15144. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15145. }
  15146. else {
  15147. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15148. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15149. }
  15150. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15151. }
  15152. texture._comparisonFunction = comparisonFunction;
  15153. };
  15154. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15155. var width = size.width || size;
  15156. var height = size.height || size;
  15157. internalTexture.baseWidth = width;
  15158. internalTexture.baseHeight = height;
  15159. internalTexture.width = width;
  15160. internalTexture.height = height;
  15161. internalTexture.isReady = true;
  15162. internalTexture.samples = 1;
  15163. internalTexture.generateMipMaps = false;
  15164. internalTexture._generateDepthBuffer = true;
  15165. internalTexture._generateStencilBuffer = generateStencil;
  15166. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15167. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15168. internalTexture._comparisonFunction = comparisonFunction;
  15169. var gl = this._gl;
  15170. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15171. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15172. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15173. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15174. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15175. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15176. if (comparisonFunction === 0) {
  15177. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15178. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15179. }
  15180. else {
  15181. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15182. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15183. }
  15184. };
  15185. /**
  15186. * Creates a depth stencil texture.
  15187. * This is only available in WebGL 2 or with the depth texture extension available.
  15188. * @param size The size of face edge in the texture.
  15189. * @param options The options defining the texture.
  15190. * @returns The texture
  15191. */
  15192. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15193. if (options.isCube) {
  15194. var width = size.width || size;
  15195. return this._createDepthStencilCubeTexture(width, options);
  15196. }
  15197. else {
  15198. return this._createDepthStencilTexture(size, options);
  15199. }
  15200. };
  15201. /**
  15202. * Creates a depth stencil texture.
  15203. * This is only available in WebGL 2 or with the depth texture extension available.
  15204. * @param size The size of face edge in the texture.
  15205. * @param options The options defining the texture.
  15206. * @returns The texture
  15207. */
  15208. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15209. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15210. if (!this._caps.depthTextureExtension) {
  15211. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15212. return internalTexture;
  15213. }
  15214. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15215. var gl = this._gl;
  15216. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15217. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15218. if (this.webGLVersion > 1) {
  15219. if (internalOptions.generateStencil) {
  15220. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15221. }
  15222. else {
  15223. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15224. }
  15225. }
  15226. else {
  15227. if (internalOptions.generateStencil) {
  15228. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15229. }
  15230. else {
  15231. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15232. }
  15233. }
  15234. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15235. return internalTexture;
  15236. };
  15237. /**
  15238. * Creates a depth stencil cube texture.
  15239. * This is only available in WebGL 2.
  15240. * @param size The size of face edge in the cube texture.
  15241. * @param options The options defining the cube texture.
  15242. * @returns The cube texture
  15243. */
  15244. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15245. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15246. internalTexture.isCube = true;
  15247. if (this.webGLVersion === 1) {
  15248. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15249. return internalTexture;
  15250. }
  15251. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15252. var gl = this._gl;
  15253. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15254. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15255. // Create the depth/stencil buffer
  15256. for (var face = 0; face < 6; face++) {
  15257. if (internalOptions.generateStencil) {
  15258. 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);
  15259. }
  15260. else {
  15261. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15262. }
  15263. }
  15264. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15265. return internalTexture;
  15266. };
  15267. /**
  15268. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15269. * @param renderTarget The render target to set the frame buffer for
  15270. */
  15271. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15272. // Create the framebuffer
  15273. var internalTexture = renderTarget.getInternalTexture();
  15274. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15275. return;
  15276. }
  15277. var gl = this._gl;
  15278. var depthStencilTexture = renderTarget.depthStencilTexture;
  15279. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15280. if (depthStencilTexture.isCube) {
  15281. if (depthStencilTexture._generateStencilBuffer) {
  15282. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15283. }
  15284. else {
  15285. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15286. }
  15287. }
  15288. else {
  15289. if (depthStencilTexture._generateStencilBuffer) {
  15290. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15291. }
  15292. else {
  15293. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15294. }
  15295. }
  15296. this.bindUnboundFramebuffer(null);
  15297. };
  15298. /**
  15299. * Creates a new render target texture
  15300. * @param size defines the size of the texture
  15301. * @param options defines the options used to create the texture
  15302. * @returns a new render target texture stored in an InternalTexture
  15303. */
  15304. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15305. var fullOptions = new RenderTargetCreationOptions();
  15306. if (options !== undefined && typeof options === "object") {
  15307. fullOptions.generateMipMaps = options.generateMipMaps;
  15308. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15309. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15310. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15311. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15312. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15313. }
  15314. else {
  15315. fullOptions.generateMipMaps = options;
  15316. fullOptions.generateDepthBuffer = true;
  15317. fullOptions.generateStencilBuffer = false;
  15318. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15319. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15320. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15321. }
  15322. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15323. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15324. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15325. }
  15326. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15327. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15328. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15329. }
  15330. var gl = this._gl;
  15331. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15332. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15333. var width = size.width || size;
  15334. var height = size.height || size;
  15335. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15336. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15337. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15338. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15339. }
  15340. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15341. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15342. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15343. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15344. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15345. // Create the framebuffer
  15346. var currentFrameBuffer = this._currentFramebuffer;
  15347. var framebuffer = gl.createFramebuffer();
  15348. this.bindUnboundFramebuffer(framebuffer);
  15349. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15350. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15351. if (fullOptions.generateMipMaps) {
  15352. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15353. }
  15354. // Unbind
  15355. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15356. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15357. this.bindUnboundFramebuffer(currentFrameBuffer);
  15358. texture._framebuffer = framebuffer;
  15359. texture.baseWidth = width;
  15360. texture.baseHeight = height;
  15361. texture.width = width;
  15362. texture.height = height;
  15363. texture.isReady = true;
  15364. texture.samples = 1;
  15365. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15366. texture.samplingMode = fullOptions.samplingMode;
  15367. texture.type = fullOptions.type;
  15368. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15369. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15370. // this.resetTextureCache();
  15371. this._internalTexturesCache.push(texture);
  15372. return texture;
  15373. };
  15374. /**
  15375. * Create a multi render target texture
  15376. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15377. * @param size defines the size of the texture
  15378. * @param options defines the creation options
  15379. * @returns the cube texture as an InternalTexture
  15380. */
  15381. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15382. var generateMipMaps = false;
  15383. var generateDepthBuffer = true;
  15384. var generateStencilBuffer = false;
  15385. var generateDepthTexture = false;
  15386. var textureCount = 1;
  15387. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15388. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15389. var types = new Array();
  15390. var samplingModes = new Array();
  15391. if (options !== undefined) {
  15392. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15393. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15394. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15395. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15396. textureCount = options.textureCount || 1;
  15397. if (options.types) {
  15398. types = options.types;
  15399. }
  15400. if (options.samplingModes) {
  15401. samplingModes = options.samplingModes;
  15402. }
  15403. }
  15404. var gl = this._gl;
  15405. // Create the framebuffer
  15406. var framebuffer = gl.createFramebuffer();
  15407. this.bindUnboundFramebuffer(framebuffer);
  15408. var width = size.width || size;
  15409. var height = size.height || size;
  15410. var textures = [];
  15411. var attachments = [];
  15412. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15413. for (var i = 0; i < textureCount; i++) {
  15414. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15415. var type = types[i] || defaultType;
  15416. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15417. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15418. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15419. }
  15420. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15421. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15422. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15423. }
  15424. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15425. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15426. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15427. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15428. }
  15429. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15430. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15431. textures.push(texture);
  15432. attachments.push(attachment);
  15433. gl.activeTexture(gl["TEXTURE" + i]);
  15434. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15439. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15440. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15441. if (generateMipMaps) {
  15442. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15443. }
  15444. // Unbind
  15445. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15446. texture._framebuffer = framebuffer;
  15447. texture._depthStencilBuffer = depthStencilBuffer;
  15448. texture.baseWidth = width;
  15449. texture.baseHeight = height;
  15450. texture.width = width;
  15451. texture.height = height;
  15452. texture.isReady = true;
  15453. texture.samples = 1;
  15454. texture.generateMipMaps = generateMipMaps;
  15455. texture.samplingMode = samplingMode;
  15456. texture.type = type;
  15457. texture._generateDepthBuffer = generateDepthBuffer;
  15458. texture._generateStencilBuffer = generateStencilBuffer;
  15459. texture._attachments = attachments;
  15460. this._internalTexturesCache.push(texture);
  15461. }
  15462. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15463. // Depth texture
  15464. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15465. gl.activeTexture(gl.TEXTURE0);
  15466. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15467. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15468. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15469. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15470. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15471. 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);
  15472. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15473. depthTexture._framebuffer = framebuffer;
  15474. depthTexture.baseWidth = width;
  15475. depthTexture.baseHeight = height;
  15476. depthTexture.width = width;
  15477. depthTexture.height = height;
  15478. depthTexture.isReady = true;
  15479. depthTexture.samples = 1;
  15480. depthTexture.generateMipMaps = generateMipMaps;
  15481. depthTexture.samplingMode = gl.NEAREST;
  15482. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15483. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15484. textures.push(depthTexture);
  15485. this._internalTexturesCache.push(depthTexture);
  15486. }
  15487. gl.drawBuffers(attachments);
  15488. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15489. this.bindUnboundFramebuffer(null);
  15490. this.resetTextureCache();
  15491. return textures;
  15492. };
  15493. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15494. if (samples === void 0) { samples = 1; }
  15495. var depthStencilBuffer = null;
  15496. var gl = this._gl;
  15497. // Create the depth/stencil buffer
  15498. if (generateStencilBuffer) {
  15499. depthStencilBuffer = gl.createRenderbuffer();
  15500. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15501. if (samples > 1) {
  15502. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15503. }
  15504. else {
  15505. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15506. }
  15507. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15508. }
  15509. else if (generateDepthBuffer) {
  15510. depthStencilBuffer = gl.createRenderbuffer();
  15511. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15512. if (samples > 1) {
  15513. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15514. }
  15515. else {
  15516. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15517. }
  15518. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15519. }
  15520. return depthStencilBuffer;
  15521. };
  15522. /**
  15523. * Updates the sample count of a render target texture
  15524. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15525. * @param texture defines the texture to update
  15526. * @param samples defines the sample count to set
  15527. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15528. */
  15529. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15530. if (this.webGLVersion < 2 || !texture) {
  15531. return 1;
  15532. }
  15533. if (texture.samples === samples) {
  15534. return samples;
  15535. }
  15536. var gl = this._gl;
  15537. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15538. // Dispose previous render buffers
  15539. if (texture._depthStencilBuffer) {
  15540. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15541. texture._depthStencilBuffer = null;
  15542. }
  15543. if (texture._MSAAFramebuffer) {
  15544. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15545. texture._MSAAFramebuffer = null;
  15546. }
  15547. if (texture._MSAARenderBuffer) {
  15548. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15549. texture._MSAARenderBuffer = null;
  15550. }
  15551. if (samples > 1) {
  15552. var framebuffer = gl.createFramebuffer();
  15553. if (!framebuffer) {
  15554. throw new Error("Unable to create multi sampled framebuffer");
  15555. }
  15556. texture._MSAAFramebuffer = framebuffer;
  15557. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15558. var colorRenderbuffer = gl.createRenderbuffer();
  15559. if (!colorRenderbuffer) {
  15560. throw new Error("Unable to create multi sampled framebuffer");
  15561. }
  15562. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15563. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15564. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15565. texture._MSAARenderBuffer = colorRenderbuffer;
  15566. }
  15567. else {
  15568. this.bindUnboundFramebuffer(texture._framebuffer);
  15569. }
  15570. texture.samples = samples;
  15571. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15572. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15573. this.bindUnboundFramebuffer(null);
  15574. return samples;
  15575. };
  15576. /**
  15577. * Update the sample count for a given multiple render target texture
  15578. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15579. * @param textures defines the textures to update
  15580. * @param samples defines the sample count to set
  15581. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15582. */
  15583. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15584. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15585. return 1;
  15586. }
  15587. if (textures[0].samples === samples) {
  15588. return samples;
  15589. }
  15590. var gl = this._gl;
  15591. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15592. // Dispose previous render buffers
  15593. if (textures[0]._depthStencilBuffer) {
  15594. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15595. textures[0]._depthStencilBuffer = null;
  15596. }
  15597. if (textures[0]._MSAAFramebuffer) {
  15598. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15599. textures[0]._MSAAFramebuffer = null;
  15600. }
  15601. for (var i = 0; i < textures.length; i++) {
  15602. if (textures[i]._MSAARenderBuffer) {
  15603. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15604. textures[i]._MSAARenderBuffer = null;
  15605. }
  15606. }
  15607. if (samples > 1) {
  15608. var framebuffer = gl.createFramebuffer();
  15609. if (!framebuffer) {
  15610. throw new Error("Unable to create multi sampled framebuffer");
  15611. }
  15612. this.bindUnboundFramebuffer(framebuffer);
  15613. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15614. var attachments = [];
  15615. for (var i = 0; i < textures.length; i++) {
  15616. var texture = textures[i];
  15617. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15618. var colorRenderbuffer = gl.createRenderbuffer();
  15619. if (!colorRenderbuffer) {
  15620. throw new Error("Unable to create multi sampled framebuffer");
  15621. }
  15622. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15623. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15624. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15625. texture._MSAAFramebuffer = framebuffer;
  15626. texture._MSAARenderBuffer = colorRenderbuffer;
  15627. texture.samples = samples;
  15628. texture._depthStencilBuffer = depthStencilBuffer;
  15629. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15630. attachments.push(attachment);
  15631. }
  15632. gl.drawBuffers(attachments);
  15633. }
  15634. else {
  15635. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15636. }
  15637. this.bindUnboundFramebuffer(null);
  15638. return samples;
  15639. };
  15640. /** @hidden */
  15641. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15642. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15643. };
  15644. /** @hidden */
  15645. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15646. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15647. };
  15648. /** @hidden */
  15649. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15650. var gl = this._gl;
  15651. var textureType = this._getWebGLTextureType(texture.type);
  15652. var format = this._getInternalFormat(texture.format);
  15653. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15654. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15655. this._bindTextureDirectly(bindTarget, texture, true);
  15656. this._unpackFlipY(texture.invertY);
  15657. var target = gl.TEXTURE_2D;
  15658. if (texture.isCube) {
  15659. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15660. }
  15661. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15662. this._bindTextureDirectly(bindTarget, null, true);
  15663. };
  15664. /**
  15665. * Creates a new render target cube texture
  15666. * @param size defines the size of the texture
  15667. * @param options defines the options used to create the texture
  15668. * @returns a new render target cube texture stored in an InternalTexture
  15669. */
  15670. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15671. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15672. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15673. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15674. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15675. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15676. }
  15677. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15678. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15679. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15680. }
  15681. var gl = this._gl;
  15682. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15683. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15684. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15685. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15686. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15687. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15688. }
  15689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15690. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15693. for (var face = 0; face < 6; face++) {
  15694. 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);
  15695. }
  15696. // Create the framebuffer
  15697. var framebuffer = gl.createFramebuffer();
  15698. this.bindUnboundFramebuffer(framebuffer);
  15699. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15700. // MipMaps
  15701. if (fullOptions.generateMipMaps) {
  15702. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15703. }
  15704. // Unbind
  15705. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15706. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15707. this.bindUnboundFramebuffer(null);
  15708. texture._framebuffer = framebuffer;
  15709. texture.width = size;
  15710. texture.height = size;
  15711. texture.isReady = true;
  15712. texture.isCube = true;
  15713. texture.samples = 1;
  15714. texture.generateMipMaps = fullOptions.generateMipMaps;
  15715. texture.samplingMode = fullOptions.samplingMode;
  15716. texture.type = fullOptions.type;
  15717. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15718. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15719. this._internalTexturesCache.push(texture);
  15720. return texture;
  15721. };
  15722. /**
  15723. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15724. * @param rootUrl defines the url where the file to load is located
  15725. * @param scene defines the current scene
  15726. * @param lodScale defines scale to apply to the mip map selection
  15727. * @param lodOffset defines offset to apply to the mip map selection
  15728. * @param onLoad defines an optional callback raised when the texture is loaded
  15729. * @param onError defines an optional callback raised if there is an issue to load the texture
  15730. * @param format defines the format of the data
  15731. * @param forcedExtension defines the extension to use to pick the right loader
  15732. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15733. * @returns the cube texture as an InternalTexture
  15734. */
  15735. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15736. var _this = this;
  15737. if (onLoad === void 0) { onLoad = null; }
  15738. if (onError === void 0) { onError = null; }
  15739. if (forcedExtension === void 0) { forcedExtension = null; }
  15740. if (createPolynomials === void 0) { createPolynomials = true; }
  15741. var callback = function (loadData) {
  15742. if (!loadData) {
  15743. if (onLoad) {
  15744. onLoad(null);
  15745. }
  15746. return;
  15747. }
  15748. var texture = loadData.texture;
  15749. if (!createPolynomials) {
  15750. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15751. }
  15752. else if (loadData.info.sphericalPolynomial) {
  15753. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15754. }
  15755. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15756. if (_this._caps.textureLOD) {
  15757. // Do not add extra process if texture lod is supported.
  15758. if (onLoad) {
  15759. onLoad(texture);
  15760. }
  15761. return;
  15762. }
  15763. var mipSlices = 3;
  15764. var gl = _this._gl;
  15765. var width = loadData.width;
  15766. if (!width) {
  15767. return;
  15768. }
  15769. var textures = [];
  15770. for (var i = 0; i < mipSlices; i++) {
  15771. //compute LOD from even spacing in smoothness (matching shader calculation)
  15772. var smoothness = i / (mipSlices - 1);
  15773. var roughness = 1 - smoothness;
  15774. var minLODIndex = lodOffset; // roughness = 0
  15775. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15776. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15777. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15778. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15779. glTextureFromLod.isCube = true;
  15780. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15782. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15783. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15784. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15785. if (loadData.isDDS) {
  15786. var info = loadData.info;
  15787. var data = loadData.data;
  15788. _this._unpackFlipY(info.isCompressed);
  15789. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15790. }
  15791. else {
  15792. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15793. }
  15794. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15795. // Wrap in a base texture for easy binding.
  15796. var lodTexture = new BABYLON.BaseTexture(scene);
  15797. lodTexture.isCube = true;
  15798. lodTexture._texture = glTextureFromLod;
  15799. glTextureFromLod.isReady = true;
  15800. textures.push(lodTexture);
  15801. }
  15802. texture._lodTextureHigh = textures[2];
  15803. texture._lodTextureMid = textures[1];
  15804. texture._lodTextureLow = textures[0];
  15805. if (onLoad) {
  15806. onLoad(texture);
  15807. }
  15808. };
  15809. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15810. };
  15811. /**
  15812. * Creates a cube texture
  15813. * @param rootUrl defines the url where the files to load is located
  15814. * @param scene defines the current scene
  15815. * @param files defines the list of files to load (1 per face)
  15816. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15817. * @param onLoad defines an optional callback raised when the texture is loaded
  15818. * @param onError defines an optional callback raised if there is an issue to load the texture
  15819. * @param format defines the format of the data
  15820. * @param forcedExtension defines the extension to use to pick the right loader
  15821. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15822. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15823. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15824. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15825. * @returns the cube texture as an InternalTexture
  15826. */
  15827. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15828. var _this = this;
  15829. if (onLoad === void 0) { onLoad = null; }
  15830. if (onError === void 0) { onError = null; }
  15831. if (forcedExtension === void 0) { forcedExtension = null; }
  15832. if (createPolynomials === void 0) { createPolynomials = false; }
  15833. if (lodScale === void 0) { lodScale = 0; }
  15834. if (lodOffset === void 0) { lodOffset = 0; }
  15835. if (fallback === void 0) { fallback = null; }
  15836. var gl = this._gl;
  15837. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15838. texture.isCube = true;
  15839. texture.url = rootUrl;
  15840. texture.generateMipMaps = !noMipmap;
  15841. texture._lodGenerationScale = lodScale;
  15842. texture._lodGenerationOffset = lodOffset;
  15843. if (!this._doNotHandleContextLost) {
  15844. texture._extension = forcedExtension;
  15845. texture._files = files;
  15846. }
  15847. var isKTX = false;
  15848. var isDDS = false;
  15849. var isEnv = false;
  15850. var lastDot = rootUrl.lastIndexOf('.');
  15851. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15852. if (this._textureFormatInUse && !fallback) {
  15853. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15854. isKTX = true;
  15855. }
  15856. else {
  15857. isDDS = (extension === ".dds");
  15858. isEnv = (extension === ".env");
  15859. }
  15860. var onerror = function (request, exception) {
  15861. if (isKTX) {
  15862. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15863. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15864. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15865. }
  15866. if (onError && request) {
  15867. onError(request.status + " " + request.statusText, exception);
  15868. }
  15869. };
  15870. if (isKTX) {
  15871. this._loadFile(rootUrl, function (data) {
  15872. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15873. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15874. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15875. _this._unpackFlipY(true);
  15876. ktx.uploadLevels(_this._gl, !noMipmap);
  15877. _this.setCubeMapTextureParams(gl, loadMipmap);
  15878. texture.width = ktx.pixelWidth;
  15879. texture.height = ktx.pixelHeight;
  15880. texture.isReady = true;
  15881. }, undefined, undefined, true, onerror);
  15882. }
  15883. else if (isEnv) {
  15884. this._loadFile(rootUrl, function (data) {
  15885. data = data;
  15886. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15887. if (info) {
  15888. texture.width = info.width;
  15889. texture.height = info.width;
  15890. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15891. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15892. texture.isReady = true;
  15893. if (onLoad) {
  15894. onLoad();
  15895. }
  15896. });
  15897. }
  15898. else if (onError) {
  15899. onError("Can not parse the environment file", null);
  15900. }
  15901. }, undefined, undefined, true, onerror);
  15902. }
  15903. else if (isDDS) {
  15904. if (files && files.length === 6) {
  15905. this._cascadeLoadFiles(scene, function (imgs) {
  15906. var info;
  15907. var loadMipmap = false;
  15908. var width = 0;
  15909. for (var index = 0; index < imgs.length; index++) {
  15910. var data = imgs[index];
  15911. info = BABYLON.DDSTools.GetDDSInfo(data);
  15912. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15913. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15914. _this._unpackFlipY(info.isCompressed);
  15915. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15916. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15917. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15918. }
  15919. texture.width = info.width;
  15920. texture.height = info.height;
  15921. texture.type = info.textureType;
  15922. width = info.width;
  15923. }
  15924. _this.setCubeMapTextureParams(gl, loadMipmap);
  15925. texture.isReady = true;
  15926. if (onLoad) {
  15927. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15928. }
  15929. }, files, onError);
  15930. }
  15931. else {
  15932. this._loadFile(rootUrl, function (data) {
  15933. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15934. if (createPolynomials) {
  15935. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15936. }
  15937. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15938. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15939. _this._unpackFlipY(info.isCompressed);
  15940. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15941. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15942. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15943. }
  15944. _this.setCubeMapTextureParams(gl, loadMipmap);
  15945. texture.width = info.width;
  15946. texture.height = info.height;
  15947. texture.isReady = true;
  15948. texture.type = info.textureType;
  15949. if (onLoad) {
  15950. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15951. }
  15952. }, undefined, undefined, true, onerror);
  15953. }
  15954. }
  15955. else {
  15956. if (!files) {
  15957. throw new Error("Cannot load cubemap because files were not defined");
  15958. }
  15959. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15960. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15961. var height = width;
  15962. _this._prepareWorkingCanvas();
  15963. if (!_this._workingCanvas || !_this._workingContext) {
  15964. return;
  15965. }
  15966. _this._workingCanvas.width = width;
  15967. _this._workingCanvas.height = height;
  15968. var faces = [
  15969. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15970. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15971. ];
  15972. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15973. _this._unpackFlipY(false);
  15974. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15975. for (var index = 0; index < faces.length; index++) {
  15976. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15977. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15978. }
  15979. if (!noMipmap) {
  15980. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15981. }
  15982. _this.setCubeMapTextureParams(gl, !noMipmap);
  15983. texture.width = width;
  15984. texture.height = height;
  15985. texture.isReady = true;
  15986. if (format) {
  15987. texture.format = format;
  15988. }
  15989. texture.onLoadedObservable.notifyObservers(texture);
  15990. texture.onLoadedObservable.clear();
  15991. if (onLoad) {
  15992. onLoad();
  15993. }
  15994. }, files, onError);
  15995. }
  15996. this._internalTexturesCache.push(texture);
  15997. return texture;
  15998. };
  15999. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  16000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16004. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16005. // this.resetTextureCache();
  16006. };
  16007. /**
  16008. * Update a raw cube texture
  16009. * @param texture defines the texture to udpdate
  16010. * @param data defines the data to store
  16011. * @param format defines the data format
  16012. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16013. * @param invertY defines if data must be stored with Y axis inverted
  16014. * @param compression defines the compression used (null by default)
  16015. * @param level defines which level of the texture to update
  16016. */
  16017. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16018. if (compression === void 0) { compression = null; }
  16019. if (level === void 0) { level = 0; }
  16020. texture._bufferViewArray = data;
  16021. texture.format = format;
  16022. texture.type = type;
  16023. texture.invertY = invertY;
  16024. texture._compression = compression;
  16025. var gl = this._gl;
  16026. var textureType = this._getWebGLTextureType(type);
  16027. var internalFormat = this._getInternalFormat(format);
  16028. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16029. var needConversion = false;
  16030. if (internalFormat === gl.RGB) {
  16031. internalFormat = gl.RGBA;
  16032. needConversion = true;
  16033. }
  16034. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16035. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16036. if (texture.width % 4 !== 0) {
  16037. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16038. }
  16039. // Data are known to be in +X +Y +Z -X -Y -Z
  16040. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16041. var faceData = data[faceIndex];
  16042. if (compression) {
  16043. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16044. }
  16045. else {
  16046. if (needConversion) {
  16047. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16048. }
  16049. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16050. }
  16051. }
  16052. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16053. if (isPot && texture.generateMipMaps && level === 0) {
  16054. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16055. }
  16056. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16057. // this.resetTextureCache();
  16058. texture.isReady = true;
  16059. };
  16060. /**
  16061. * Creates a new raw cube texture
  16062. * @param data defines the array of data to use to create each face
  16063. * @param size defines the size of the textures
  16064. * @param format defines the format of the data
  16065. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16066. * @param generateMipMaps defines if the engine should generate the mip levels
  16067. * @param invertY defines if data must be stored with Y axis inverted
  16068. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16069. * @param compression defines the compression used (null by default)
  16070. * @returns the cube texture as an InternalTexture
  16071. */
  16072. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16073. if (compression === void 0) { compression = null; }
  16074. var gl = this._gl;
  16075. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16076. texture.isCube = true;
  16077. texture.generateMipMaps = generateMipMaps;
  16078. texture.format = format;
  16079. texture.type = type;
  16080. if (!this._doNotHandleContextLost) {
  16081. texture._bufferViewArray = data;
  16082. }
  16083. var textureType = this._getWebGLTextureType(type);
  16084. var internalFormat = this._getInternalFormat(format);
  16085. if (internalFormat === gl.RGB) {
  16086. internalFormat = gl.RGBA;
  16087. }
  16088. var width = size;
  16089. var height = width;
  16090. texture.width = width;
  16091. texture.height = height;
  16092. // Double check on POT to generate Mips.
  16093. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16094. if (!isPot) {
  16095. generateMipMaps = false;
  16096. }
  16097. // Upload data if needed. The texture won't be ready until then.
  16098. if (data) {
  16099. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16100. }
  16101. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16102. // Filters
  16103. if (data && generateMipMaps) {
  16104. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16105. }
  16106. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16107. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16108. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16109. }
  16110. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16111. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16112. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16113. }
  16114. else {
  16115. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16116. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16117. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16118. }
  16119. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16120. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16121. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16122. return texture;
  16123. };
  16124. /**
  16125. * Creates a new raw cube texture from a specified url
  16126. * @param url defines the url where the data is located
  16127. * @param scene defines the current scene
  16128. * @param size defines the size of the textures
  16129. * @param format defines the format of the data
  16130. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16131. * @param noMipmap defines if the engine should avoid generating the mip levels
  16132. * @param callback defines a callback used to extract texture data from loaded data
  16133. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16134. * @param onLoad defines a callback called when texture is loaded
  16135. * @param onError defines a callback called if there is an error
  16136. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16137. * @param invertY defines if data must be stored with Y axis inverted
  16138. * @returns the cube texture as an InternalTexture
  16139. */
  16140. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16141. var _this = this;
  16142. if (onLoad === void 0) { onLoad = null; }
  16143. if (onError === void 0) { onError = null; }
  16144. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16145. if (invertY === void 0) { invertY = false; }
  16146. var gl = this._gl;
  16147. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16148. scene._addPendingData(texture);
  16149. texture.url = url;
  16150. this._internalTexturesCache.push(texture);
  16151. var onerror = function (request, exception) {
  16152. scene._removePendingData(texture);
  16153. if (onError && request) {
  16154. onError(request.status + " " + request.statusText, exception);
  16155. }
  16156. };
  16157. var internalCallback = function (data) {
  16158. var width = texture.width;
  16159. var faceDataArrays = callback(data);
  16160. if (!faceDataArrays) {
  16161. return;
  16162. }
  16163. if (mipmapGenerator) {
  16164. var textureType = _this._getWebGLTextureType(type);
  16165. var internalFormat = _this._getInternalFormat(format);
  16166. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16167. var needConversion = false;
  16168. if (internalFormat === gl.RGB) {
  16169. internalFormat = gl.RGBA;
  16170. needConversion = true;
  16171. }
  16172. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16173. _this._unpackFlipY(false);
  16174. var mipData = mipmapGenerator(faceDataArrays);
  16175. for (var level = 0; level < mipData.length; level++) {
  16176. var mipSize = width >> level;
  16177. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16178. var mipFaceData = mipData[level][faceIndex];
  16179. if (needConversion) {
  16180. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16181. }
  16182. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16183. }
  16184. }
  16185. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16186. }
  16187. else {
  16188. texture.generateMipMaps = !noMipmap;
  16189. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16190. }
  16191. texture.isReady = true;
  16192. // this.resetTextureCache();
  16193. scene._removePendingData(texture);
  16194. if (onLoad) {
  16195. onLoad();
  16196. }
  16197. };
  16198. this._loadFile(url, function (data) {
  16199. internalCallback(data);
  16200. }, undefined, scene.database, true, onerror);
  16201. return texture;
  16202. };
  16203. ;
  16204. /**
  16205. * Update a raw 3D texture
  16206. * @param texture defines the texture to update
  16207. * @param data defines the data to store
  16208. * @param format defines the data format
  16209. * @param invertY defines if data must be stored with Y axis inverted
  16210. * @param compression defines the used compression (can be null)
  16211. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16212. */
  16213. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16214. if (compression === void 0) { compression = null; }
  16215. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16216. var internalType = this._getWebGLTextureType(textureType);
  16217. var internalFormat = this._getInternalFormat(format);
  16218. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16219. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16220. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16221. if (!this._doNotHandleContextLost) {
  16222. texture._bufferView = data;
  16223. texture.format = format;
  16224. texture.invertY = invertY;
  16225. texture._compression = compression;
  16226. }
  16227. if (texture.width % 4 !== 0) {
  16228. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16229. }
  16230. if (compression && data) {
  16231. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16232. }
  16233. else {
  16234. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16235. }
  16236. if (texture.generateMipMaps) {
  16237. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16238. }
  16239. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16240. // this.resetTextureCache();
  16241. texture.isReady = true;
  16242. };
  16243. /**
  16244. * Creates a new raw 3D texture
  16245. * @param data defines the data used to create the texture
  16246. * @param width defines the width of the texture
  16247. * @param height defines the height of the texture
  16248. * @param depth defines the depth of the texture
  16249. * @param format defines the format of the texture
  16250. * @param generateMipMaps defines if the engine must generate mip levels
  16251. * @param invertY defines if data must be stored with Y axis inverted
  16252. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16253. * @param compression defines the compressed used (can be null)
  16254. * @param textureType defines the compressed used (can be null)
  16255. * @returns a new raw 3D texture (stored in an InternalTexture)
  16256. */
  16257. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16258. if (compression === void 0) { compression = null; }
  16259. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16260. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16261. texture.baseWidth = width;
  16262. texture.baseHeight = height;
  16263. texture.baseDepth = depth;
  16264. texture.width = width;
  16265. texture.height = height;
  16266. texture.depth = depth;
  16267. texture.format = format;
  16268. texture.type = textureType;
  16269. texture.generateMipMaps = generateMipMaps;
  16270. texture.samplingMode = samplingMode;
  16271. texture.is3D = true;
  16272. if (!this._doNotHandleContextLost) {
  16273. texture._bufferView = data;
  16274. }
  16275. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16276. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16277. // Filters
  16278. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16279. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16280. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16281. if (generateMipMaps) {
  16282. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16283. }
  16284. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16285. this._internalTexturesCache.push(texture);
  16286. return texture;
  16287. };
  16288. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16289. var gl = this._gl;
  16290. if (!gl) {
  16291. return;
  16292. }
  16293. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16294. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16295. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16296. if (!noMipmap && !isCompressed) {
  16297. gl.generateMipmap(gl.TEXTURE_2D);
  16298. }
  16299. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16300. // this.resetTextureCache();
  16301. if (scene) {
  16302. scene._removePendingData(texture);
  16303. }
  16304. texture.onLoadedObservable.notifyObservers(texture);
  16305. texture.onLoadedObservable.clear();
  16306. };
  16307. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16308. var _this = this;
  16309. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16310. var maxTextureSize = this.getCaps().maxTextureSize;
  16311. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16312. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16313. var gl = this._gl;
  16314. if (!gl) {
  16315. return;
  16316. }
  16317. if (!texture._webGLTexture) {
  16318. // this.resetTextureCache();
  16319. if (scene) {
  16320. scene._removePendingData(texture);
  16321. }
  16322. return;
  16323. }
  16324. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16325. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16326. texture.baseWidth = width;
  16327. texture.baseHeight = height;
  16328. texture.width = potWidth;
  16329. texture.height = potHeight;
  16330. texture.isReady = true;
  16331. if (processFunction(potWidth, potHeight, function () {
  16332. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16333. })) {
  16334. // Returning as texture needs extra async steps
  16335. return;
  16336. }
  16337. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16338. };
  16339. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16340. // Create new RGBA data container.
  16341. var rgbaData;
  16342. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16343. rgbaData = new Float32Array(width * height * 4);
  16344. }
  16345. else {
  16346. rgbaData = new Uint32Array(width * height * 4);
  16347. }
  16348. // Convert each pixel.
  16349. for (var x = 0; x < width; x++) {
  16350. for (var y = 0; y < height; y++) {
  16351. var index = (y * width + x) * 3;
  16352. var newIndex = (y * width + x) * 4;
  16353. // Map Old Value to new value.
  16354. rgbaData[newIndex + 0] = rgbData[index + 0];
  16355. rgbaData[newIndex + 1] = rgbData[index + 1];
  16356. rgbaData[newIndex + 2] = rgbData[index + 2];
  16357. // Add fully opaque alpha channel.
  16358. rgbaData[newIndex + 3] = 1;
  16359. }
  16360. }
  16361. return rgbaData;
  16362. };
  16363. /** @hidden */
  16364. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16365. var gl = this._gl;
  16366. if (texture._framebuffer) {
  16367. gl.deleteFramebuffer(texture._framebuffer);
  16368. texture._framebuffer = null;
  16369. }
  16370. if (texture._depthStencilBuffer) {
  16371. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16372. texture._depthStencilBuffer = null;
  16373. }
  16374. if (texture._MSAAFramebuffer) {
  16375. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16376. texture._MSAAFramebuffer = null;
  16377. }
  16378. if (texture._MSAARenderBuffer) {
  16379. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16380. texture._MSAARenderBuffer = null;
  16381. }
  16382. };
  16383. /** @hidden */
  16384. Engine.prototype._releaseTexture = function (texture) {
  16385. var gl = this._gl;
  16386. this._releaseFramebufferObjects(texture);
  16387. gl.deleteTexture(texture._webGLTexture);
  16388. // Unbind channels
  16389. this.unbindAllTextures();
  16390. var index = this._internalTexturesCache.indexOf(texture);
  16391. if (index !== -1) {
  16392. this._internalTexturesCache.splice(index, 1);
  16393. }
  16394. // Integrated fixed lod samplers.
  16395. if (texture._lodTextureHigh) {
  16396. texture._lodTextureHigh.dispose();
  16397. }
  16398. if (texture._lodTextureMid) {
  16399. texture._lodTextureMid.dispose();
  16400. }
  16401. if (texture._lodTextureLow) {
  16402. texture._lodTextureLow.dispose();
  16403. }
  16404. // Set output texture of post process to null if the texture has been released/disposed
  16405. this.scenes.forEach(function (scene) {
  16406. scene.postProcesses.forEach(function (postProcess) {
  16407. if (postProcess._outputTexture == texture) {
  16408. postProcess._outputTexture = null;
  16409. }
  16410. });
  16411. scene.cameras.forEach(function (camera) {
  16412. camera._postProcesses.forEach(function (postProcess) {
  16413. if (postProcess) {
  16414. if (postProcess._outputTexture == texture) {
  16415. postProcess._outputTexture = null;
  16416. }
  16417. }
  16418. });
  16419. });
  16420. });
  16421. };
  16422. Engine.prototype.setProgram = function (program) {
  16423. if (this._currentProgram !== program) {
  16424. this._gl.useProgram(program);
  16425. this._currentProgram = program;
  16426. }
  16427. };
  16428. /**
  16429. * Binds an effect to the webGL context
  16430. * @param effect defines the effect to bind
  16431. */
  16432. Engine.prototype.bindSamplers = function (effect) {
  16433. this.setProgram(effect.getProgram());
  16434. var samplers = effect.getSamplers();
  16435. for (var index = 0; index < samplers.length; index++) {
  16436. var uniform = effect.getUniform(samplers[index]);
  16437. if (uniform) {
  16438. this._boundUniforms[index] = uniform;
  16439. }
  16440. }
  16441. this._currentEffect = null;
  16442. };
  16443. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16444. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16445. return;
  16446. }
  16447. // Remove
  16448. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16449. // Bind last to it
  16450. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16451. // Bind to dummy
  16452. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16453. };
  16454. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16455. if (!internalTexture) {
  16456. return -1;
  16457. }
  16458. internalTexture._initialSlot = channel;
  16459. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16460. if (channel !== internalTexture._designatedSlot) {
  16461. this._textureCollisions.addCount(1, false);
  16462. }
  16463. }
  16464. else {
  16465. if (channel !== internalTexture._designatedSlot) {
  16466. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16467. return internalTexture._designatedSlot;
  16468. }
  16469. else {
  16470. // No slot for this texture, let's pick a new one (if we find a free slot)
  16471. if (this._nextFreeTextureSlots.length) {
  16472. return this._nextFreeTextureSlots[0];
  16473. }
  16474. // We need to recycle the oldest bound texture, sorry.
  16475. this._textureCollisions.addCount(1, false);
  16476. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16477. }
  16478. }
  16479. }
  16480. return channel;
  16481. };
  16482. Engine.prototype._linkTrackers = function (previous, next) {
  16483. previous.next = next;
  16484. next.previous = previous;
  16485. };
  16486. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16487. var currentSlot = internalTexture._designatedSlot;
  16488. if (currentSlot === -1) {
  16489. return -1;
  16490. }
  16491. internalTexture._designatedSlot = -1;
  16492. if (this.disableTextureBindingOptimization) {
  16493. return -1;
  16494. }
  16495. // Remove from bound list
  16496. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16497. // Free the slot
  16498. this._boundTexturesCache[currentSlot] = null;
  16499. this._nextFreeTextureSlots.push(currentSlot);
  16500. return currentSlot;
  16501. };
  16502. Engine.prototype._activateCurrentTexture = function () {
  16503. if (this._currentTextureChannel !== this._activeChannel) {
  16504. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16505. this._currentTextureChannel = this._activeChannel;
  16506. }
  16507. };
  16508. /** @hidden */
  16509. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16510. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16511. if (force === void 0) { force = false; }
  16512. var wasPreviouslyBound = false;
  16513. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16514. this._activeChannel = texture._designatedSlot;
  16515. }
  16516. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16517. var isTextureForRendering = texture && texture._initialSlot > -1;
  16518. if (currentTextureBound !== texture || force) {
  16519. if (currentTextureBound) {
  16520. this._removeDesignatedSlot(currentTextureBound);
  16521. }
  16522. this._activateCurrentTexture();
  16523. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16524. this._boundTexturesCache[this._activeChannel] = texture;
  16525. if (texture) {
  16526. if (!this.disableTextureBindingOptimization) {
  16527. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16528. if (slotIndex > -1) {
  16529. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16530. }
  16531. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16532. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16533. }
  16534. texture._designatedSlot = this._activeChannel;
  16535. }
  16536. }
  16537. else if (forTextureDataUpdate) {
  16538. wasPreviouslyBound = true;
  16539. this._activateCurrentTexture();
  16540. }
  16541. if (isTextureForRendering && !forTextureDataUpdate) {
  16542. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16543. }
  16544. return wasPreviouslyBound;
  16545. };
  16546. /** @hidden */
  16547. Engine.prototype._bindTexture = function (channel, texture) {
  16548. if (channel < 0) {
  16549. return;
  16550. }
  16551. if (texture) {
  16552. channel = this._getCorrectTextureChannel(channel, texture);
  16553. }
  16554. this._activeChannel = channel;
  16555. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16556. };
  16557. /**
  16558. * Sets a texture to the webGL context from a postprocess
  16559. * @param channel defines the channel to use
  16560. * @param postProcess defines the source postprocess
  16561. */
  16562. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16563. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16564. };
  16565. /**
  16566. * Binds the output of the passed in post process to the texture channel specified
  16567. * @param channel The channel the texture should be bound to
  16568. * @param postProcess The post process which's output should be bound
  16569. */
  16570. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16571. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16572. };
  16573. /**
  16574. * Unbind all textures from the webGL context
  16575. */
  16576. Engine.prototype.unbindAllTextures = function () {
  16577. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16578. this._activeChannel = channel;
  16579. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16580. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16581. if (this.webGLVersion > 1) {
  16582. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16583. }
  16584. }
  16585. };
  16586. /**
  16587. * Sets a texture to the according uniform.
  16588. * @param channel The texture channel
  16589. * @param uniform The uniform to set
  16590. * @param texture The texture to apply
  16591. */
  16592. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16593. if (channel < 0) {
  16594. return;
  16595. }
  16596. if (uniform) {
  16597. this._boundUniforms[channel] = uniform;
  16598. }
  16599. this._setTexture(channel, texture);
  16600. };
  16601. /**
  16602. * Sets a depth stencil texture from a render target to the according uniform.
  16603. * @param channel The texture channel
  16604. * @param uniform The uniform to set
  16605. * @param texture The render target texture containing the depth stencil texture to apply
  16606. */
  16607. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16608. if (channel < 0) {
  16609. return;
  16610. }
  16611. if (uniform) {
  16612. this._boundUniforms[channel] = uniform;
  16613. }
  16614. if (!texture || !texture.depthStencilTexture) {
  16615. this._setTexture(channel, null);
  16616. }
  16617. else {
  16618. this._setTexture(channel, texture, false, true);
  16619. }
  16620. };
  16621. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16622. var uniform = this._boundUniforms[sourceSlot];
  16623. if (uniform._currentState === destination) {
  16624. return;
  16625. }
  16626. this._gl.uniform1i(uniform, destination);
  16627. uniform._currentState = destination;
  16628. };
  16629. Engine.prototype._getTextureWrapMode = function (mode) {
  16630. switch (mode) {
  16631. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16632. return this._gl.REPEAT;
  16633. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16634. return this._gl.CLAMP_TO_EDGE;
  16635. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16636. return this._gl.MIRRORED_REPEAT;
  16637. }
  16638. return this._gl.REPEAT;
  16639. };
  16640. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16641. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16642. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16643. // Not ready?
  16644. if (!texture) {
  16645. if (this._boundTexturesCache[channel] != null) {
  16646. this._activeChannel = channel;
  16647. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16648. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16649. if (this.webGLVersion > 1) {
  16650. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16651. }
  16652. }
  16653. return false;
  16654. }
  16655. // Video
  16656. if (texture.video) {
  16657. this._activeChannel = channel;
  16658. texture.update();
  16659. }
  16660. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16661. texture.delayLoad();
  16662. return false;
  16663. }
  16664. var internalTexture;
  16665. if (depthStencilTexture) {
  16666. internalTexture = texture.depthStencilTexture;
  16667. }
  16668. else if (texture.isReady()) {
  16669. internalTexture = texture.getInternalTexture();
  16670. }
  16671. else if (texture.isCube) {
  16672. internalTexture = this.emptyCubeTexture;
  16673. }
  16674. else if (texture.is3D) {
  16675. internalTexture = this.emptyTexture3D;
  16676. }
  16677. else {
  16678. internalTexture = this.emptyTexture;
  16679. }
  16680. if (!isPartOfTextureArray) {
  16681. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16682. }
  16683. var needToBind = true;
  16684. if (this._boundTexturesCache[channel] === internalTexture) {
  16685. this._moveBoundTextureOnTop(internalTexture);
  16686. if (!isPartOfTextureArray) {
  16687. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16688. }
  16689. needToBind = false;
  16690. }
  16691. this._activeChannel = channel;
  16692. if (internalTexture && internalTexture.is3D) {
  16693. if (needToBind) {
  16694. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16695. }
  16696. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16697. internalTexture._cachedWrapU = texture.wrapU;
  16698. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16699. }
  16700. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16701. internalTexture._cachedWrapV = texture.wrapV;
  16702. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16703. }
  16704. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16705. internalTexture._cachedWrapR = texture.wrapR;
  16706. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16707. }
  16708. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16709. }
  16710. else if (internalTexture && internalTexture.isCube) {
  16711. if (needToBind) {
  16712. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16713. }
  16714. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16715. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16716. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16717. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16718. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16719. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16720. }
  16721. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16722. }
  16723. else {
  16724. if (needToBind) {
  16725. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16726. }
  16727. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16728. internalTexture._cachedWrapU = texture.wrapU;
  16729. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16730. }
  16731. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16732. internalTexture._cachedWrapV = texture.wrapV;
  16733. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16734. }
  16735. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16736. }
  16737. return true;
  16738. };
  16739. /**
  16740. * Sets an array of texture to the webGL context
  16741. * @param channel defines the channel where the texture array must be set
  16742. * @param uniform defines the associated uniform location
  16743. * @param textures defines the array of textures to bind
  16744. */
  16745. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16746. if (channel < 0 || !uniform) {
  16747. return;
  16748. }
  16749. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16750. this._textureUnits = new Int32Array(textures.length);
  16751. }
  16752. for (var i = 0; i < textures.length; i++) {
  16753. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16754. }
  16755. this._gl.uniform1iv(uniform, this._textureUnits);
  16756. for (var index = 0; index < textures.length; index++) {
  16757. this._setTexture(this._textureUnits[index], textures[index], true);
  16758. }
  16759. };
  16760. /** @hidden */
  16761. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16762. var internalTexture = texture.getInternalTexture();
  16763. if (!internalTexture) {
  16764. return;
  16765. }
  16766. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16767. var value = texture.anisotropicFilteringLevel;
  16768. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16769. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16770. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16771. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16772. }
  16773. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16774. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16775. internalTexture._cachedAnisotropicFilteringLevel = value;
  16776. }
  16777. };
  16778. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16779. this._bindTextureDirectly(target, texture, true, true);
  16780. this._gl.texParameterf(target, parameter, value);
  16781. };
  16782. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16783. if (texture) {
  16784. this._bindTextureDirectly(target, texture, true, true);
  16785. }
  16786. this._gl.texParameteri(target, parameter, value);
  16787. };
  16788. /**
  16789. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16790. * @param x defines the x coordinate of the rectangle where pixels must be read
  16791. * @param y defines the y coordinate of the rectangle where pixels must be read
  16792. * @param width defines the width of the rectangle where pixels must be read
  16793. * @param height defines the height of the rectangle where pixels must be read
  16794. * @returns a Uint8Array containing RGBA colors
  16795. */
  16796. Engine.prototype.readPixels = function (x, y, width, height) {
  16797. var data = new Uint8Array(height * width * 4);
  16798. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16799. return data;
  16800. };
  16801. /**
  16802. * Add an externaly attached data from its key.
  16803. * This method call will fail and return false, if such key already exists.
  16804. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16805. * @param key the unique key that identifies the data
  16806. * @param data the data object to associate to the key for this Engine instance
  16807. * @return true if no such key were already present and the data was added successfully, false otherwise
  16808. */
  16809. Engine.prototype.addExternalData = function (key, data) {
  16810. if (!this._externalData) {
  16811. this._externalData = new BABYLON.StringDictionary();
  16812. }
  16813. return this._externalData.add(key, data);
  16814. };
  16815. /**
  16816. * Get an externaly attached data from its key
  16817. * @param key the unique key that identifies the data
  16818. * @return the associated data, if present (can be null), or undefined if not present
  16819. */
  16820. Engine.prototype.getExternalData = function (key) {
  16821. if (!this._externalData) {
  16822. this._externalData = new BABYLON.StringDictionary();
  16823. }
  16824. return this._externalData.get(key);
  16825. };
  16826. /**
  16827. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16828. * @param key the unique key that identifies the data
  16829. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16830. * @return the associated data, can be null if the factory returned null.
  16831. */
  16832. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16833. if (!this._externalData) {
  16834. this._externalData = new BABYLON.StringDictionary();
  16835. }
  16836. return this._externalData.getOrAddWithFactory(key, factory);
  16837. };
  16838. /**
  16839. * Remove an externaly attached data from the Engine instance
  16840. * @param key the unique key that identifies the data
  16841. * @return true if the data was successfully removed, false if it doesn't exist
  16842. */
  16843. Engine.prototype.removeExternalData = function (key) {
  16844. if (!this._externalData) {
  16845. this._externalData = new BABYLON.StringDictionary();
  16846. }
  16847. return this._externalData.remove(key);
  16848. };
  16849. /**
  16850. * Unbind all vertex attributes from the webGL context
  16851. */
  16852. Engine.prototype.unbindAllAttributes = function () {
  16853. if (this._mustWipeVertexAttributes) {
  16854. this._mustWipeVertexAttributes = false;
  16855. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16856. this._gl.disableVertexAttribArray(i);
  16857. this._vertexAttribArraysEnabled[i] = false;
  16858. this._currentBufferPointers[i].active = false;
  16859. }
  16860. return;
  16861. }
  16862. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16863. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16864. continue;
  16865. }
  16866. this._gl.disableVertexAttribArray(i);
  16867. this._vertexAttribArraysEnabled[i] = false;
  16868. this._currentBufferPointers[i].active = false;
  16869. }
  16870. };
  16871. /**
  16872. * 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
  16873. */
  16874. Engine.prototype.releaseEffects = function () {
  16875. for (var name in this._compiledEffects) {
  16876. this._deleteProgram(this._compiledEffects[name]._program);
  16877. }
  16878. this._compiledEffects = {};
  16879. };
  16880. /**
  16881. * Dispose and release all associated resources
  16882. */
  16883. Engine.prototype.dispose = function () {
  16884. this.hideLoadingUI();
  16885. this.stopRenderLoop();
  16886. // Release postProcesses
  16887. while (this.postProcesses.length) {
  16888. this.postProcesses[0].dispose();
  16889. }
  16890. // Empty texture
  16891. if (this._emptyTexture) {
  16892. this._releaseTexture(this._emptyTexture);
  16893. this._emptyTexture = null;
  16894. }
  16895. if (this._emptyCubeTexture) {
  16896. this._releaseTexture(this._emptyCubeTexture);
  16897. this._emptyCubeTexture = null;
  16898. }
  16899. // Rescale PP
  16900. if (this._rescalePostProcess) {
  16901. this._rescalePostProcess.dispose();
  16902. }
  16903. // Release scenes
  16904. while (this.scenes.length) {
  16905. this.scenes[0].dispose();
  16906. }
  16907. // Release audio engine
  16908. if (Engine.audioEngine) {
  16909. Engine.audioEngine.dispose();
  16910. }
  16911. // Release effects
  16912. this.releaseEffects();
  16913. // Unbind
  16914. this.unbindAllAttributes();
  16915. this._boundUniforms = [];
  16916. if (this._dummyFramebuffer) {
  16917. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16918. }
  16919. //WebVR
  16920. this.disableVR();
  16921. // Events
  16922. if (BABYLON.Tools.IsWindowObjectExist()) {
  16923. window.removeEventListener("blur", this._onBlur);
  16924. window.removeEventListener("focus", this._onFocus);
  16925. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16926. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16927. if (this._renderingCanvas) {
  16928. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16929. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16930. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16931. if (!this._doNotHandleContextLost) {
  16932. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16933. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16934. }
  16935. }
  16936. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16937. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16938. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16939. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16940. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16941. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16942. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16943. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16944. if (this._onVrDisplayConnect) {
  16945. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16946. if (this._onVrDisplayDisconnect) {
  16947. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16948. }
  16949. if (this._onVrDisplayPresentChange) {
  16950. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16951. }
  16952. this._onVrDisplayConnect = null;
  16953. this._onVrDisplayDisconnect = null;
  16954. }
  16955. }
  16956. // Remove from Instances
  16957. var index = Engine.Instances.indexOf(this);
  16958. if (index >= 0) {
  16959. Engine.Instances.splice(index, 1);
  16960. }
  16961. this._workingCanvas = null;
  16962. this._workingContext = null;
  16963. this._currentBufferPointers = [];
  16964. this._renderingCanvas = null;
  16965. this._currentProgram = null;
  16966. this._bindedRenderFunction = null;
  16967. this.onResizeObservable.clear();
  16968. this.onCanvasBlurObservable.clear();
  16969. this.onCanvasFocusObservable.clear();
  16970. this.onCanvasPointerOutObservable.clear();
  16971. this.onBeginFrameObservable.clear();
  16972. this.onEndFrameObservable.clear();
  16973. BABYLON.Effect.ResetCache();
  16974. // Abort active requests
  16975. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16976. var request = _a[_i];
  16977. request.abort();
  16978. }
  16979. };
  16980. // Loading screen
  16981. /**
  16982. * Display the loading screen
  16983. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16984. */
  16985. Engine.prototype.displayLoadingUI = function () {
  16986. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16987. return;
  16988. }
  16989. var loadingScreen = this.loadingScreen;
  16990. if (loadingScreen) {
  16991. loadingScreen.displayLoadingUI();
  16992. }
  16993. };
  16994. /**
  16995. * Hide the loading screen
  16996. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16997. */
  16998. Engine.prototype.hideLoadingUI = function () {
  16999. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17000. return;
  17001. }
  17002. var loadingScreen = this.loadingScreen;
  17003. if (loadingScreen) {
  17004. loadingScreen.hideLoadingUI();
  17005. }
  17006. };
  17007. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17008. /**
  17009. * Gets the current loading screen object
  17010. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17011. */
  17012. get: function () {
  17013. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17014. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17015. return this._loadingScreen;
  17016. },
  17017. /**
  17018. * Sets the current loading screen object
  17019. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17020. */
  17021. set: function (loadingScreen) {
  17022. this._loadingScreen = loadingScreen;
  17023. },
  17024. enumerable: true,
  17025. configurable: true
  17026. });
  17027. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17028. /**
  17029. * Sets the current loading screen text
  17030. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17031. */
  17032. set: function (text) {
  17033. this.loadingScreen.loadingUIText = text;
  17034. },
  17035. enumerable: true,
  17036. configurable: true
  17037. });
  17038. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17039. /**
  17040. * Sets the current loading screen background color
  17041. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17042. */
  17043. set: function (color) {
  17044. this.loadingScreen.loadingUIBackgroundColor = color;
  17045. },
  17046. enumerable: true,
  17047. configurable: true
  17048. });
  17049. /**
  17050. * Attach a new callback raised when context lost event is fired
  17051. * @param callback defines the callback to call
  17052. */
  17053. Engine.prototype.attachContextLostEvent = function (callback) {
  17054. if (this._renderingCanvas) {
  17055. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17056. }
  17057. };
  17058. /**
  17059. * Attach a new callback raised when context restored event is fired
  17060. * @param callback defines the callback to call
  17061. */
  17062. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17063. if (this._renderingCanvas) {
  17064. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17065. }
  17066. };
  17067. /**
  17068. * Gets the source code of the vertex shader associated with a specific webGL program
  17069. * @param program defines the program to use
  17070. * @returns a string containing the source code of the vertex shader associated with the program
  17071. */
  17072. Engine.prototype.getVertexShaderSource = function (program) {
  17073. var shaders = this._gl.getAttachedShaders(program);
  17074. if (!shaders) {
  17075. return null;
  17076. }
  17077. return this._gl.getShaderSource(shaders[0]);
  17078. };
  17079. /**
  17080. * Gets the source code of the fragment shader associated with a specific webGL program
  17081. * @param program defines the program to use
  17082. * @returns a string containing the source code of the fragment shader associated with the program
  17083. */
  17084. Engine.prototype.getFragmentShaderSource = function (program) {
  17085. var shaders = this._gl.getAttachedShaders(program);
  17086. if (!shaders) {
  17087. return null;
  17088. }
  17089. return this._gl.getShaderSource(shaders[1]);
  17090. };
  17091. /**
  17092. * Get the current error code of the webGL context
  17093. * @returns the error code
  17094. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17095. */
  17096. Engine.prototype.getError = function () {
  17097. return this._gl.getError();
  17098. };
  17099. // FPS
  17100. /**
  17101. * Gets the current framerate
  17102. * @returns a number representing the framerate
  17103. */
  17104. Engine.prototype.getFps = function () {
  17105. return this._fps;
  17106. };
  17107. /**
  17108. * Gets the time spent between current and previous frame
  17109. * @returns a number representing the delta time in ms
  17110. */
  17111. Engine.prototype.getDeltaTime = function () {
  17112. return this._deltaTime;
  17113. };
  17114. Engine.prototype._measureFps = function () {
  17115. this._performanceMonitor.sampleFrame();
  17116. this._fps = this._performanceMonitor.averageFPS;
  17117. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17118. };
  17119. /** @hidden */
  17120. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17121. if (faceIndex === void 0) { faceIndex = -1; }
  17122. if (level === void 0) { level = 0; }
  17123. var gl = this._gl;
  17124. if (!this._dummyFramebuffer) {
  17125. var dummy = gl.createFramebuffer();
  17126. if (!dummy) {
  17127. throw new Error("Unable to create dummy framebuffer");
  17128. }
  17129. this._dummyFramebuffer = dummy;
  17130. }
  17131. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17132. if (faceIndex > -1) {
  17133. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17134. }
  17135. else {
  17136. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17137. }
  17138. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17139. var buffer;
  17140. switch (readType) {
  17141. case gl.UNSIGNED_BYTE:
  17142. buffer = new Uint8Array(4 * width * height);
  17143. readType = gl.UNSIGNED_BYTE;
  17144. break;
  17145. default:
  17146. buffer = new Float32Array(4 * width * height);
  17147. readType = gl.FLOAT;
  17148. break;
  17149. }
  17150. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17151. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17152. return buffer;
  17153. };
  17154. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17155. if (this._webGLVersion > 1) {
  17156. return this._caps.colorBufferFloat;
  17157. }
  17158. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17159. };
  17160. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17161. if (this._webGLVersion > 1) {
  17162. return this._caps.colorBufferFloat;
  17163. }
  17164. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17165. };
  17166. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17167. Engine.prototype._canRenderToFramebuffer = function (type) {
  17168. var gl = this._gl;
  17169. //clear existing errors
  17170. while (gl.getError() !== gl.NO_ERROR) { }
  17171. var successful = true;
  17172. var texture = gl.createTexture();
  17173. gl.bindTexture(gl.TEXTURE_2D, texture);
  17174. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17175. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17176. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17177. var fb = gl.createFramebuffer();
  17178. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17179. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17180. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17181. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17182. successful = successful && (gl.getError() === gl.NO_ERROR);
  17183. //try render by clearing frame buffer's color buffer
  17184. if (successful) {
  17185. gl.clear(gl.COLOR_BUFFER_BIT);
  17186. successful = successful && (gl.getError() === gl.NO_ERROR);
  17187. }
  17188. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17189. if (successful) {
  17190. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17191. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17192. var readFormat = gl.RGBA;
  17193. var readType = gl.UNSIGNED_BYTE;
  17194. var buffer = new Uint8Array(4);
  17195. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17196. successful = successful && (gl.getError() === gl.NO_ERROR);
  17197. }
  17198. //clean up
  17199. gl.deleteTexture(texture);
  17200. gl.deleteFramebuffer(fb);
  17201. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17202. //clear accumulated errors
  17203. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17204. return successful;
  17205. };
  17206. /** @hidden */
  17207. Engine.prototype._getWebGLTextureType = function (type) {
  17208. if (type === Engine.TEXTURETYPE_FLOAT) {
  17209. return this._gl.FLOAT;
  17210. }
  17211. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17212. // Add Half Float Constant.
  17213. return this._gl.HALF_FLOAT_OES;
  17214. }
  17215. return this._gl.UNSIGNED_BYTE;
  17216. };
  17217. ;
  17218. Engine.prototype._getInternalFormat = function (format) {
  17219. var internalFormat = this._gl.RGBA;
  17220. switch (format) {
  17221. case Engine.TEXTUREFORMAT_ALPHA:
  17222. internalFormat = this._gl.ALPHA;
  17223. break;
  17224. case Engine.TEXTUREFORMAT_LUMINANCE:
  17225. internalFormat = this._gl.LUMINANCE;
  17226. break;
  17227. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17228. internalFormat = this._gl.LUMINANCE_ALPHA;
  17229. break;
  17230. case Engine.TEXTUREFORMAT_RGB:
  17231. internalFormat = this._gl.RGB;
  17232. break;
  17233. case Engine.TEXTUREFORMAT_RGBA:
  17234. internalFormat = this._gl.RGBA;
  17235. break;
  17236. case Engine.TEXTUREFORMAT_R:
  17237. internalFormat = this._gl.RED;
  17238. break;
  17239. case Engine.TEXTUREFORMAT_RG:
  17240. internalFormat = this._gl.RG;
  17241. break;
  17242. }
  17243. return internalFormat;
  17244. };
  17245. /** @hidden */
  17246. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17247. if (this._webGLVersion === 1) {
  17248. if (format !== undefined) {
  17249. switch (format) {
  17250. case Engine.TEXTUREFORMAT_LUMINANCE:
  17251. return this._gl.LUMINANCE;
  17252. case Engine.TEXTUREFORMAT_ALPHA:
  17253. return this._gl.ALPHA;
  17254. }
  17255. }
  17256. return this._gl.RGBA;
  17257. }
  17258. if (type === Engine.TEXTURETYPE_FLOAT) {
  17259. if (format !== undefined) {
  17260. switch (format) {
  17261. case Engine.TEXTUREFORMAT_R:
  17262. return this._gl.R32F;
  17263. case Engine.TEXTUREFORMAT_RG:
  17264. return this._gl.RG32F;
  17265. case Engine.TEXTUREFORMAT_RGB:
  17266. return this._gl.RGB32F;
  17267. }
  17268. }
  17269. return this._gl.RGBA32F;
  17270. }
  17271. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17272. if (format) {
  17273. switch (format) {
  17274. case Engine.TEXTUREFORMAT_R:
  17275. return this._gl.R16F;
  17276. case Engine.TEXTUREFORMAT_RG:
  17277. return this._gl.RG16F;
  17278. case Engine.TEXTUREFORMAT_RGB:
  17279. return this._gl.RGB16F;
  17280. }
  17281. }
  17282. return this._gl.RGBA16F;
  17283. }
  17284. if (format !== undefined) {
  17285. switch (format) {
  17286. case Engine.TEXTUREFORMAT_LUMINANCE:
  17287. return this._gl.LUMINANCE;
  17288. case Engine.TEXTUREFORMAT_RGB:
  17289. return this._gl.RGB;
  17290. case Engine.TEXTUREFORMAT_R:
  17291. return this._gl.R8;
  17292. case Engine.TEXTUREFORMAT_RG:
  17293. return this._gl.RG8;
  17294. case Engine.TEXTUREFORMAT_ALPHA:
  17295. return this._gl.ALPHA;
  17296. }
  17297. }
  17298. return this._gl.RGBA;
  17299. };
  17300. ;
  17301. /** @hidden */
  17302. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17303. if (type === Engine.TEXTURETYPE_FLOAT) {
  17304. return this._gl.RGBA32F;
  17305. }
  17306. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17307. return this._gl.RGBA16F;
  17308. }
  17309. return this._gl.RGBA8;
  17310. };
  17311. ;
  17312. /**
  17313. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17314. * @return the new query
  17315. */
  17316. Engine.prototype.createQuery = function () {
  17317. return this._gl.createQuery();
  17318. };
  17319. /**
  17320. * Delete and release a webGL query
  17321. * @param query defines the query to delete
  17322. * @return the current engine
  17323. */
  17324. Engine.prototype.deleteQuery = function (query) {
  17325. this._gl.deleteQuery(query);
  17326. return this;
  17327. };
  17328. /**
  17329. * Check if a given query has resolved and got its value
  17330. * @param query defines the query to check
  17331. * @returns true if the query got its value
  17332. */
  17333. Engine.prototype.isQueryResultAvailable = function (query) {
  17334. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17335. };
  17336. /**
  17337. * Gets the value of a given query
  17338. * @param query defines the query to check
  17339. * @returns the value of the query
  17340. */
  17341. Engine.prototype.getQueryResult = function (query) {
  17342. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17343. };
  17344. /**
  17345. * Initiates an occlusion query
  17346. * @param algorithmType defines the algorithm to use
  17347. * @param query defines the query to use
  17348. * @returns the current engine
  17349. * @see http://doc.babylonjs.com/features/occlusionquery
  17350. */
  17351. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17352. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17353. this._gl.beginQuery(glAlgorithm, query);
  17354. return this;
  17355. };
  17356. /**
  17357. * Ends an occlusion query
  17358. * @see http://doc.babylonjs.com/features/occlusionquery
  17359. * @param algorithmType defines the algorithm to use
  17360. * @returns the current engine
  17361. */
  17362. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17363. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17364. this._gl.endQuery(glAlgorithm);
  17365. return this;
  17366. };
  17367. /* Time queries */
  17368. Engine.prototype._createTimeQuery = function () {
  17369. var timerQuery = this._caps.timerQuery;
  17370. if (timerQuery.createQueryEXT) {
  17371. return timerQuery.createQueryEXT();
  17372. }
  17373. return this.createQuery();
  17374. };
  17375. Engine.prototype._deleteTimeQuery = function (query) {
  17376. var timerQuery = this._caps.timerQuery;
  17377. if (timerQuery.deleteQueryEXT) {
  17378. timerQuery.deleteQueryEXT(query);
  17379. return;
  17380. }
  17381. this.deleteQuery(query);
  17382. };
  17383. Engine.prototype._getTimeQueryResult = function (query) {
  17384. var timerQuery = this._caps.timerQuery;
  17385. if (timerQuery.getQueryObjectEXT) {
  17386. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17387. }
  17388. return this.getQueryResult(query);
  17389. };
  17390. Engine.prototype._getTimeQueryAvailability = function (query) {
  17391. var timerQuery = this._caps.timerQuery;
  17392. if (timerQuery.getQueryObjectEXT) {
  17393. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17394. }
  17395. return this.isQueryResultAvailable(query);
  17396. };
  17397. /**
  17398. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17399. * Please note that only one query can be issued at a time
  17400. * @returns a time token used to track the time span
  17401. */
  17402. Engine.prototype.startTimeQuery = function () {
  17403. var timerQuery = this._caps.timerQuery;
  17404. if (!timerQuery) {
  17405. return null;
  17406. }
  17407. var token = new BABYLON._TimeToken();
  17408. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17409. if (this._caps.canUseTimestampForTimerQuery) {
  17410. token._startTimeQuery = this._createTimeQuery();
  17411. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17412. }
  17413. else {
  17414. if (this._currentNonTimestampToken) {
  17415. return this._currentNonTimestampToken;
  17416. }
  17417. token._timeElapsedQuery = this._createTimeQuery();
  17418. if (timerQuery.beginQueryEXT) {
  17419. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17420. }
  17421. else {
  17422. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17423. }
  17424. this._currentNonTimestampToken = token;
  17425. }
  17426. return token;
  17427. };
  17428. /**
  17429. * Ends a time query
  17430. * @param token defines the token used to measure the time span
  17431. * @returns the time spent (in ns)
  17432. */
  17433. Engine.prototype.endTimeQuery = function (token) {
  17434. var timerQuery = this._caps.timerQuery;
  17435. if (!timerQuery || !token) {
  17436. return -1;
  17437. }
  17438. if (this._caps.canUseTimestampForTimerQuery) {
  17439. if (!token._startTimeQuery) {
  17440. return -1;
  17441. }
  17442. if (!token._endTimeQuery) {
  17443. token._endTimeQuery = this._createTimeQuery();
  17444. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17445. }
  17446. }
  17447. else if (!token._timeElapsedQueryEnded) {
  17448. if (!token._timeElapsedQuery) {
  17449. return -1;
  17450. }
  17451. if (timerQuery.endQueryEXT) {
  17452. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17453. }
  17454. else {
  17455. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17456. }
  17457. token._timeElapsedQueryEnded = true;
  17458. }
  17459. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17460. var available = false;
  17461. if (token._endTimeQuery) {
  17462. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17463. }
  17464. else if (token._timeElapsedQuery) {
  17465. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17466. }
  17467. if (available && !disjoint) {
  17468. var result = 0;
  17469. if (this._caps.canUseTimestampForTimerQuery) {
  17470. if (!token._startTimeQuery || !token._endTimeQuery) {
  17471. return -1;
  17472. }
  17473. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17474. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17475. result = timeEnd - timeStart;
  17476. this._deleteTimeQuery(token._startTimeQuery);
  17477. this._deleteTimeQuery(token._endTimeQuery);
  17478. token._startTimeQuery = null;
  17479. token._endTimeQuery = null;
  17480. }
  17481. else {
  17482. if (!token._timeElapsedQuery) {
  17483. return -1;
  17484. }
  17485. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17486. this._deleteTimeQuery(token._timeElapsedQuery);
  17487. token._timeElapsedQuery = null;
  17488. token._timeElapsedQueryEnded = false;
  17489. this._currentNonTimestampToken = null;
  17490. }
  17491. return result;
  17492. }
  17493. return -1;
  17494. };
  17495. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17496. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17497. };
  17498. // Transform feedback
  17499. /**
  17500. * Creates a webGL transform feedback object
  17501. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17502. * @returns the webGL transform feedback object
  17503. */
  17504. Engine.prototype.createTransformFeedback = function () {
  17505. return this._gl.createTransformFeedback();
  17506. };
  17507. /**
  17508. * Delete a webGL transform feedback object
  17509. * @param value defines the webGL transform feedback object to delete
  17510. */
  17511. Engine.prototype.deleteTransformFeedback = function (value) {
  17512. this._gl.deleteTransformFeedback(value);
  17513. };
  17514. /**
  17515. * Bind a webGL transform feedback object to the webgl context
  17516. * @param value defines the webGL transform feedback object to bind
  17517. */
  17518. Engine.prototype.bindTransformFeedback = function (value) {
  17519. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17520. };
  17521. /**
  17522. * Begins a transform feedback operation
  17523. * @param usePoints defines if points or triangles must be used
  17524. */
  17525. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17526. if (usePoints === void 0) { usePoints = true; }
  17527. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17528. };
  17529. /**
  17530. * Ends a transform feedback operation
  17531. */
  17532. Engine.prototype.endTransformFeedback = function () {
  17533. this._gl.endTransformFeedback();
  17534. };
  17535. /**
  17536. * Specify the varyings to use with transform feedback
  17537. * @param program defines the associated webGL program
  17538. * @param value defines the list of strings representing the varying names
  17539. */
  17540. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17541. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17542. };
  17543. /**
  17544. * Bind a webGL buffer for a transform feedback operation
  17545. * @param value defines the webGL buffer to bind
  17546. */
  17547. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17548. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17549. };
  17550. /** @hidden */
  17551. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17552. var _this = this;
  17553. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17554. this._activeRequests.push(request);
  17555. request.onCompleteObservable.add(function (request) {
  17556. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17557. });
  17558. return request;
  17559. };
  17560. /** @hidden */
  17561. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17562. var _this = this;
  17563. return new Promise(function (resolve, reject) {
  17564. _this._loadFile(url, function (data) {
  17565. resolve(data);
  17566. }, undefined, database, useArrayBuffer, function (request, exception) {
  17567. reject(exception);
  17568. });
  17569. });
  17570. };
  17571. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17572. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17573. var onload = function (data) {
  17574. loadedFiles[index] = data;
  17575. loadedFiles._internalCount++;
  17576. if (loadedFiles._internalCount === 6) {
  17577. onfinish(loadedFiles);
  17578. }
  17579. };
  17580. var onerror = function (request, exception) {
  17581. if (onErrorCallBack && request) {
  17582. onErrorCallBack(request.status + " " + request.statusText, exception);
  17583. }
  17584. };
  17585. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17586. };
  17587. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17588. if (onError === void 0) { onError = null; }
  17589. var loadedFiles = [];
  17590. loadedFiles._internalCount = 0;
  17591. for (var index = 0; index < 6; index++) {
  17592. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17593. }
  17594. };
  17595. // Statics
  17596. /**
  17597. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17598. * @returns true if the engine can be created
  17599. * @ignorenaming
  17600. */
  17601. Engine.isSupported = function () {
  17602. try {
  17603. var tempcanvas = document.createElement("canvas");
  17604. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17605. return gl != null && !!window.WebGLRenderingContext;
  17606. }
  17607. catch (e) {
  17608. return false;
  17609. }
  17610. };
  17611. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17612. Engine.ExceptionList = [
  17613. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17614. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17615. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17616. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17617. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17618. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17619. ];
  17620. /** Gets the list of created engines */
  17621. Engine.Instances = new Array();
  17622. // Const statics
  17623. Engine._ALPHA_DISABLE = 0;
  17624. Engine._ALPHA_ADD = 1;
  17625. Engine._ALPHA_COMBINE = 2;
  17626. Engine._ALPHA_SUBTRACT = 3;
  17627. Engine._ALPHA_MULTIPLY = 4;
  17628. Engine._ALPHA_MAXIMIZED = 5;
  17629. Engine._ALPHA_ONEONE = 6;
  17630. Engine._ALPHA_PREMULTIPLIED = 7;
  17631. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17632. Engine._ALPHA_INTERPOLATE = 9;
  17633. Engine._ALPHA_SCREENMODE = 10;
  17634. Engine._DELAYLOADSTATE_NONE = 0;
  17635. Engine._DELAYLOADSTATE_LOADED = 1;
  17636. Engine._DELAYLOADSTATE_LOADING = 2;
  17637. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17638. Engine._TEXTUREFORMAT_ALPHA = 0;
  17639. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17640. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17641. Engine._TEXTUREFORMAT_RGB = 4;
  17642. Engine._TEXTUREFORMAT_RGBA = 5;
  17643. Engine._TEXTUREFORMAT_R = 6;
  17644. Engine._TEXTUREFORMAT_RG = 7;
  17645. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17646. Engine._TEXTURETYPE_FLOAT = 1;
  17647. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17648. // Depht or Stencil test Constants.
  17649. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17650. 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.
  17651. 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.
  17652. 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.
  17653. 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.
  17654. 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.
  17655. 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.
  17656. 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.
  17657. // Stencil Actions Constants.
  17658. Engine._KEEP = 0x1E00;
  17659. Engine._REPLACE = 0x1E01;
  17660. Engine._INCR = 0x1E02;
  17661. Engine._DECR = 0x1E03;
  17662. Engine._INVERT = 0x150A;
  17663. Engine._INCR_WRAP = 0x8507;
  17664. Engine._DECR_WRAP = 0x8508;
  17665. // Texture rescaling mode
  17666. Engine._SCALEMODE_FLOOR = 1;
  17667. Engine._SCALEMODE_NEAREST = 2;
  17668. Engine._SCALEMODE_CEILING = 3;
  17669. // Updatable statics so stick with vars here
  17670. /**
  17671. * Gets or sets the epsilon value used by collision engine
  17672. */
  17673. Engine.CollisionsEpsilon = 0.001;
  17674. /**
  17675. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17676. */
  17677. Engine.CodeRepository = "src/";
  17678. /**
  17679. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17680. */
  17681. Engine.ShadersRepository = "src/Shaders/";
  17682. return Engine;
  17683. }());
  17684. BABYLON.Engine = Engine;
  17685. })(BABYLON || (BABYLON = {}));
  17686. //# sourceMappingURL=babylon.engine.js.map
  17687. var BABYLON;
  17688. (function (BABYLON) {
  17689. /**
  17690. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17691. */
  17692. var Node = /** @class */ (function () {
  17693. /**
  17694. * Creates a new Node
  17695. * @param {string} name - the name and id to be given to this node
  17696. * @param {BABYLON.Scene} the scene this node will be added to
  17697. */
  17698. function Node(name, scene) {
  17699. if (scene === void 0) { scene = null; }
  17700. /**
  17701. * Gets or sets a string used to store user defined state for the node
  17702. */
  17703. this.state = "";
  17704. /**
  17705. * Gets or sets an object used to store user defined information for the node
  17706. */
  17707. this.metadata = null;
  17708. /**
  17709. * Gets or sets a boolean used to define if the node must be serialized
  17710. */
  17711. this.doNotSerialize = false;
  17712. /** @hidden */
  17713. this._isDisposed = false;
  17714. /**
  17715. * Gets a list of Animations associated with the node
  17716. */
  17717. this.animations = new Array();
  17718. this._ranges = {};
  17719. this._isEnabled = true;
  17720. this._isReady = true;
  17721. /** @hidden */
  17722. this._currentRenderId = -1;
  17723. this._parentRenderId = -1;
  17724. this._childRenderId = -1;
  17725. this._animationPropertiesOverride = null;
  17726. /**
  17727. * An event triggered when the mesh is disposed
  17728. */
  17729. this.onDisposeObservable = new BABYLON.Observable();
  17730. // Behaviors
  17731. this._behaviors = new Array();
  17732. this.name = name;
  17733. this.id = name;
  17734. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17735. this.uniqueId = this._scene.getUniqueId();
  17736. this._initCache();
  17737. }
  17738. /**
  17739. * Gets a boolean indicating if the node has been disposed
  17740. * @returns true if the node was disposed
  17741. */
  17742. Node.prototype.isDisposed = function () {
  17743. return this._isDisposed;
  17744. };
  17745. Object.defineProperty(Node.prototype, "parent", {
  17746. get: function () {
  17747. return this._parentNode;
  17748. },
  17749. /**
  17750. * Gets or sets the parent of the node
  17751. */
  17752. set: function (parent) {
  17753. if (this._parentNode === parent) {
  17754. return;
  17755. }
  17756. // Remove self from list of children of parent
  17757. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17758. var index = this._parentNode._children.indexOf(this);
  17759. if (index !== -1) {
  17760. this._parentNode._children.splice(index, 1);
  17761. }
  17762. }
  17763. // Store new parent
  17764. this._parentNode = parent;
  17765. // Add as child to new parent
  17766. if (this._parentNode) {
  17767. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17768. this._parentNode._children = new Array();
  17769. }
  17770. this._parentNode._children.push(this);
  17771. }
  17772. },
  17773. enumerable: true,
  17774. configurable: true
  17775. });
  17776. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17777. /**
  17778. * Gets or sets the animation properties override
  17779. */
  17780. get: function () {
  17781. if (!this._animationPropertiesOverride) {
  17782. return this._scene.animationPropertiesOverride;
  17783. }
  17784. return this._animationPropertiesOverride;
  17785. },
  17786. set: function (value) {
  17787. this._animationPropertiesOverride = value;
  17788. },
  17789. enumerable: true,
  17790. configurable: true
  17791. });
  17792. /**
  17793. * Gets a string idenfifying the name of the class
  17794. * @returns "Node" string
  17795. */
  17796. Node.prototype.getClassName = function () {
  17797. return "Node";
  17798. };
  17799. Object.defineProperty(Node.prototype, "onDispose", {
  17800. /**
  17801. * Sets a callback that will be raised when the node will be disposed
  17802. */
  17803. set: function (callback) {
  17804. if (this._onDisposeObserver) {
  17805. this.onDisposeObservable.remove(this._onDisposeObserver);
  17806. }
  17807. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17808. },
  17809. enumerable: true,
  17810. configurable: true
  17811. });
  17812. /**
  17813. * Gets the scene of the node
  17814. * @returns a {BABYLON.Scene}
  17815. */
  17816. Node.prototype.getScene = function () {
  17817. return this._scene;
  17818. };
  17819. /**
  17820. * Gets the engine of the node
  17821. * @returns a {BABYLON.Engine}
  17822. */
  17823. Node.prototype.getEngine = function () {
  17824. return this._scene.getEngine();
  17825. };
  17826. /**
  17827. * Attach a behavior to the node
  17828. * @see http://doc.babylonjs.com/features/behaviour
  17829. * @param behavior defines the behavior to attach
  17830. * @returns the current Node
  17831. */
  17832. Node.prototype.addBehavior = function (behavior) {
  17833. var _this = this;
  17834. var index = this._behaviors.indexOf(behavior);
  17835. if (index !== -1) {
  17836. return this;
  17837. }
  17838. behavior.init();
  17839. if (this._scene.isLoading) {
  17840. // We defer the attach when the scene will be loaded
  17841. this._scene.onDataLoadedObservable.addOnce(function () {
  17842. behavior.attach(_this);
  17843. });
  17844. }
  17845. else {
  17846. behavior.attach(this);
  17847. }
  17848. this._behaviors.push(behavior);
  17849. return this;
  17850. };
  17851. /**
  17852. * Remove an attached behavior
  17853. * @see http://doc.babylonjs.com/features/behaviour
  17854. * @param behavior defines the behavior to attach
  17855. * @returns the current Node
  17856. */
  17857. Node.prototype.removeBehavior = function (behavior) {
  17858. var index = this._behaviors.indexOf(behavior);
  17859. if (index === -1) {
  17860. return this;
  17861. }
  17862. this._behaviors[index].detach();
  17863. this._behaviors.splice(index, 1);
  17864. return this;
  17865. };
  17866. Object.defineProperty(Node.prototype, "behaviors", {
  17867. /**
  17868. * Gets the list of attached behaviors
  17869. * @see http://doc.babylonjs.com/features/behaviour
  17870. */
  17871. get: function () {
  17872. return this._behaviors;
  17873. },
  17874. enumerable: true,
  17875. configurable: true
  17876. });
  17877. /**
  17878. * Gets an attached behavior by name
  17879. * @param name defines the name of the behavior to look for
  17880. * @see http://doc.babylonjs.com/features/behaviour
  17881. * @returns null if behavior was not found else the requested behavior
  17882. */
  17883. Node.prototype.getBehaviorByName = function (name) {
  17884. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17885. var behavior = _a[_i];
  17886. if (behavior.name === name) {
  17887. return behavior;
  17888. }
  17889. }
  17890. return null;
  17891. };
  17892. /**
  17893. * Returns the world matrix of the node
  17894. * @returns a matrix containing the node's world matrix
  17895. */
  17896. Node.prototype.getWorldMatrix = function () {
  17897. return BABYLON.Matrix.Identity();
  17898. };
  17899. /** @hidden */
  17900. Node.prototype._getWorldMatrixDeterminant = function () {
  17901. return 1;
  17902. };
  17903. // override it in derived class if you add new variables to the cache
  17904. // and call the parent class method
  17905. /** @hidden */
  17906. Node.prototype._initCache = function () {
  17907. this._cache = {};
  17908. this._cache.parent = undefined;
  17909. };
  17910. /** @hidden */
  17911. Node.prototype.updateCache = function (force) {
  17912. if (!force && this.isSynchronized())
  17913. return;
  17914. this._cache.parent = this.parent;
  17915. this._updateCache();
  17916. };
  17917. // override it in derived class if you add new variables to the cache
  17918. // and call the parent class method if !ignoreParentClass
  17919. /** @hidden */
  17920. Node.prototype._updateCache = function (ignoreParentClass) {
  17921. };
  17922. // override it in derived class if you add new variables to the cache
  17923. /** @hidden */
  17924. Node.prototype._isSynchronized = function () {
  17925. return true;
  17926. };
  17927. /** @hidden */
  17928. Node.prototype._markSyncedWithParent = function () {
  17929. if (this.parent) {
  17930. this._parentRenderId = this.parent._childRenderId;
  17931. }
  17932. };
  17933. /** @hidden */
  17934. Node.prototype.isSynchronizedWithParent = function () {
  17935. if (!this.parent) {
  17936. return true;
  17937. }
  17938. if (this._parentRenderId !== this.parent._childRenderId) {
  17939. return false;
  17940. }
  17941. return this.parent.isSynchronized();
  17942. };
  17943. /** @hidden */
  17944. Node.prototype.isSynchronized = function (updateCache) {
  17945. var check = this.hasNewParent();
  17946. check = check || !this.isSynchronizedWithParent();
  17947. check = check || !this._isSynchronized();
  17948. if (updateCache)
  17949. this.updateCache(true);
  17950. return !check;
  17951. };
  17952. /** @hidden */
  17953. Node.prototype.hasNewParent = function (update) {
  17954. if (this._cache.parent === this.parent)
  17955. return false;
  17956. if (update)
  17957. this._cache.parent = this.parent;
  17958. return true;
  17959. };
  17960. /**
  17961. * Is this node ready to be used/rendered
  17962. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17963. * @return true if the node is ready
  17964. */
  17965. Node.prototype.isReady = function (completeCheck) {
  17966. if (completeCheck === void 0) { completeCheck = false; }
  17967. return this._isReady;
  17968. };
  17969. /**
  17970. * Is this node enabled?
  17971. * 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
  17972. * @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
  17973. * @return whether this node (and its parent) is enabled
  17974. */
  17975. Node.prototype.isEnabled = function (checkAncestors) {
  17976. if (checkAncestors === void 0) { checkAncestors = true; }
  17977. if (checkAncestors === false) {
  17978. return this._isEnabled;
  17979. }
  17980. if (this._isEnabled === false) {
  17981. return false;
  17982. }
  17983. if (this.parent !== undefined && this.parent !== null) {
  17984. return this.parent.isEnabled(checkAncestors);
  17985. }
  17986. return true;
  17987. };
  17988. /**
  17989. * Set the enabled state of this node
  17990. * @param value defines the new enabled state
  17991. */
  17992. Node.prototype.setEnabled = function (value) {
  17993. this._isEnabled = value;
  17994. };
  17995. /**
  17996. * Is this node a descendant of the given node?
  17997. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17998. * @param ancestor defines the parent node to inspect
  17999. * @returns a boolean indicating if this node is a descendant of the given node
  18000. */
  18001. Node.prototype.isDescendantOf = function (ancestor) {
  18002. if (this.parent) {
  18003. if (this.parent === ancestor) {
  18004. return true;
  18005. }
  18006. return this.parent.isDescendantOf(ancestor);
  18007. }
  18008. return false;
  18009. };
  18010. /** @hidden */
  18011. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18012. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18013. if (!this._children) {
  18014. return;
  18015. }
  18016. for (var index = 0; index < this._children.length; index++) {
  18017. var item = this._children[index];
  18018. if (!predicate || predicate(item)) {
  18019. results.push(item);
  18020. }
  18021. if (!directDescendantsOnly) {
  18022. item._getDescendants(results, false, predicate);
  18023. }
  18024. }
  18025. };
  18026. /**
  18027. * Will return all nodes that have this node as ascendant
  18028. * @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
  18029. * @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
  18030. * @return all children nodes of all types
  18031. */
  18032. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18033. var results = new Array();
  18034. this._getDescendants(results, directDescendantsOnly, predicate);
  18035. return results;
  18036. };
  18037. /**
  18038. * Get all child-meshes of this node
  18039. * @param directDescendantsOnly defines if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered
  18040. * @param predicate defines an optional predicate that will be called on every evaluated child, the predicate must return true for a given child to be part of the result, otherwise it will be ignored
  18041. * @returns an array of {BABYLON.AbstractMesh}
  18042. */
  18043. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18044. var results = [];
  18045. this._getDescendants(results, directDescendantsOnly, function (node) {
  18046. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18047. });
  18048. return results;
  18049. };
  18050. /**
  18051. * Get all child-transformNodes of this node
  18052. * @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
  18053. * @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
  18054. * @returns an array of {BABYLON.TransformNode}
  18055. */
  18056. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18057. var results = [];
  18058. this._getDescendants(results, directDescendantsOnly, function (node) {
  18059. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18060. });
  18061. return results;
  18062. };
  18063. /**
  18064. * Get all direct children of this node
  18065. * @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
  18066. * @returns an array of {BABYLON.Node}
  18067. */
  18068. Node.prototype.getChildren = function (predicate) {
  18069. return this.getDescendants(true, predicate);
  18070. };
  18071. /** @hidden */
  18072. Node.prototype._setReady = function (state) {
  18073. if (state === this._isReady) {
  18074. return;
  18075. }
  18076. if (!state) {
  18077. this._isReady = false;
  18078. return;
  18079. }
  18080. if (this.onReady) {
  18081. this.onReady(this);
  18082. }
  18083. this._isReady = true;
  18084. };
  18085. /**
  18086. * Get an animation by name
  18087. * @param name defines the name of the animation to look for
  18088. * @returns null if not found else the requested animation
  18089. */
  18090. Node.prototype.getAnimationByName = function (name) {
  18091. for (var i = 0; i < this.animations.length; i++) {
  18092. var animation = this.animations[i];
  18093. if (animation.name === name) {
  18094. return animation;
  18095. }
  18096. }
  18097. return null;
  18098. };
  18099. /**
  18100. * Creates an animation range for this node
  18101. * @param name defines the name of the range
  18102. * @param from defines the starting key
  18103. * @param to defines the end key
  18104. */
  18105. Node.prototype.createAnimationRange = function (name, from, to) {
  18106. // check name not already in use
  18107. if (!this._ranges[name]) {
  18108. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18109. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18110. if (this.animations[i]) {
  18111. this.animations[i].createRange(name, from, to);
  18112. }
  18113. }
  18114. }
  18115. };
  18116. /**
  18117. * Delete a specific animation range
  18118. * @param name defines the name of the range to delete
  18119. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18120. */
  18121. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18122. if (deleteFrames === void 0) { deleteFrames = true; }
  18123. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18124. if (this.animations[i]) {
  18125. this.animations[i].deleteRange(name, deleteFrames);
  18126. }
  18127. }
  18128. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18129. };
  18130. /**
  18131. * Get an animation range by name
  18132. * @param name defines the name of the animation range to look for
  18133. * @returns null if not found else the requested animation range
  18134. */
  18135. Node.prototype.getAnimationRange = function (name) {
  18136. return this._ranges[name];
  18137. };
  18138. /**
  18139. * Will start the animation sequence
  18140. * @param name defines the range frames for animation sequence
  18141. * @param loop defines if the animation should loop (false by default)
  18142. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18143. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18144. * @returns the object created for this animation. If range does not exist, it will return null
  18145. */
  18146. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18147. var range = this.getAnimationRange(name);
  18148. if (!range) {
  18149. return null;
  18150. }
  18151. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18152. };
  18153. /**
  18154. * Serialize animation ranges into a JSON compatible object
  18155. * @returns serialization object
  18156. */
  18157. Node.prototype.serializeAnimationRanges = function () {
  18158. var serializationRanges = [];
  18159. for (var name in this._ranges) {
  18160. var localRange = this._ranges[name];
  18161. if (!localRange) {
  18162. continue;
  18163. }
  18164. var range = {};
  18165. range.name = name;
  18166. range.from = localRange.from;
  18167. range.to = localRange.to;
  18168. serializationRanges.push(range);
  18169. }
  18170. return serializationRanges;
  18171. };
  18172. /**
  18173. * Computes the world matrix of the node
  18174. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18175. * @returns the world matrix
  18176. */
  18177. Node.prototype.computeWorldMatrix = function (force) {
  18178. return BABYLON.Matrix.Identity();
  18179. };
  18180. /**
  18181. * Releases resources associated with this node.
  18182. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18183. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18184. */
  18185. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18186. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18187. if (!doNotRecurse) {
  18188. var nodes = this.getDescendants(true);
  18189. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18190. var node = nodes_1[_i];
  18191. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18192. }
  18193. }
  18194. else {
  18195. var transformNodes = this.getChildTransformNodes(true);
  18196. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18197. var transformNode = transformNodes_1[_a];
  18198. transformNode.parent = null;
  18199. transformNode.computeWorldMatrix(true);
  18200. }
  18201. }
  18202. this.parent = null;
  18203. // Callback
  18204. this.onDisposeObservable.notifyObservers(this);
  18205. this.onDisposeObservable.clear();
  18206. // Behaviors
  18207. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18208. var behavior = _c[_b];
  18209. behavior.detach();
  18210. }
  18211. this._behaviors = [];
  18212. this._isDisposed = true;
  18213. };
  18214. /**
  18215. * Parse animation range data from a serialization object and store them into a given node
  18216. * @param node defines where to store the animation ranges
  18217. * @param parsedNode defines the serialization object to read data from
  18218. * @param scene defines the hosting scene
  18219. */
  18220. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18221. if (parsedNode.ranges) {
  18222. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18223. var data = parsedNode.ranges[index];
  18224. node.createAnimationRange(data.name, data.from, data.to);
  18225. }
  18226. }
  18227. };
  18228. __decorate([
  18229. BABYLON.serialize()
  18230. ], Node.prototype, "name", void 0);
  18231. __decorate([
  18232. BABYLON.serialize()
  18233. ], Node.prototype, "id", void 0);
  18234. __decorate([
  18235. BABYLON.serialize()
  18236. ], Node.prototype, "uniqueId", void 0);
  18237. __decorate([
  18238. BABYLON.serialize()
  18239. ], Node.prototype, "state", void 0);
  18240. __decorate([
  18241. BABYLON.serialize()
  18242. ], Node.prototype, "metadata", void 0);
  18243. return Node;
  18244. }());
  18245. BABYLON.Node = Node;
  18246. })(BABYLON || (BABYLON = {}));
  18247. //# sourceMappingURL=babylon.node.js.map
  18248. var BABYLON;
  18249. (function (BABYLON) {
  18250. var BoundingSphere = /** @class */ (function () {
  18251. /**
  18252. * Creates a new bounding sphere
  18253. * @param min defines the minimum vector (in local space)
  18254. * @param max defines the maximum vector (in local space)
  18255. */
  18256. function BoundingSphere(min, max) {
  18257. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18258. this.reConstruct(min, max);
  18259. }
  18260. /**
  18261. * Recreates the entire bounding sphere from scratch
  18262. * @param min defines the new minimum vector (in local space)
  18263. * @param max defines the new maximum vector (in local space)
  18264. */
  18265. BoundingSphere.prototype.reConstruct = function (min, max) {
  18266. this.minimum = min.clone();
  18267. this.maximum = max.clone();
  18268. var distance = BABYLON.Vector3.Distance(min, max);
  18269. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18270. this.radius = distance * 0.5;
  18271. this.centerWorld = BABYLON.Vector3.Zero();
  18272. this._update(BABYLON.Matrix.Identity());
  18273. };
  18274. // Methods
  18275. BoundingSphere.prototype._update = function (world) {
  18276. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18277. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18278. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18279. };
  18280. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18281. for (var i = 0; i < 6; i++) {
  18282. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18283. return false;
  18284. }
  18285. return true;
  18286. };
  18287. BoundingSphere.prototype.intersectsPoint = function (point) {
  18288. var x = this.centerWorld.x - point.x;
  18289. var y = this.centerWorld.y - point.y;
  18290. var z = this.centerWorld.z - point.z;
  18291. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18292. if (this.radiusWorld < distance)
  18293. return false;
  18294. return true;
  18295. };
  18296. // Statics
  18297. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18298. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18299. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18300. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18301. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18302. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18303. return false;
  18304. return true;
  18305. };
  18306. return BoundingSphere;
  18307. }());
  18308. BABYLON.BoundingSphere = BoundingSphere;
  18309. })(BABYLON || (BABYLON = {}));
  18310. //# sourceMappingURL=babylon.boundingSphere.js.map
  18311. var BABYLON;
  18312. (function (BABYLON) {
  18313. var BoundingBox = /** @class */ (function () {
  18314. /**
  18315. * Creates a new bounding box
  18316. * @param min defines the minimum vector (in local space)
  18317. * @param max defines the maximum vector (in local space)
  18318. */
  18319. function BoundingBox(min, max) {
  18320. this.vectorsWorld = new Array();
  18321. this.reConstruct(min, max);
  18322. }
  18323. // Methods
  18324. /**
  18325. * Recreates the entire bounding box from scratch
  18326. * @param min defines the new minimum vector (in local space)
  18327. * @param max defines the new maximum vector (in local space)
  18328. */
  18329. BoundingBox.prototype.reConstruct = function (min, max) {
  18330. this.minimum = min.clone();
  18331. this.maximum = max.clone();
  18332. // Bounding vectors
  18333. this.vectors = new Array();
  18334. this.vectors.push(this.minimum.clone());
  18335. this.vectors.push(this.maximum.clone());
  18336. this.vectors.push(this.minimum.clone());
  18337. this.vectors[2].x = this.maximum.x;
  18338. this.vectors.push(this.minimum.clone());
  18339. this.vectors[3].y = this.maximum.y;
  18340. this.vectors.push(this.minimum.clone());
  18341. this.vectors[4].z = this.maximum.z;
  18342. this.vectors.push(this.maximum.clone());
  18343. this.vectors[5].z = this.minimum.z;
  18344. this.vectors.push(this.maximum.clone());
  18345. this.vectors[6].x = this.minimum.x;
  18346. this.vectors.push(this.maximum.clone());
  18347. this.vectors[7].y = this.minimum.y;
  18348. // OBB
  18349. this.center = this.maximum.add(this.minimum).scale(0.5);
  18350. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18351. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18352. // World
  18353. for (var index = 0; index < this.vectors.length; index++) {
  18354. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18355. }
  18356. this.minimumWorld = BABYLON.Vector3.Zero();
  18357. this.maximumWorld = BABYLON.Vector3.Zero();
  18358. this.centerWorld = BABYLON.Vector3.Zero();
  18359. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18360. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18361. };
  18362. BoundingBox.prototype.getWorldMatrix = function () {
  18363. return this._worldMatrix;
  18364. };
  18365. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18366. this._worldMatrix.copyFrom(matrix);
  18367. return this;
  18368. };
  18369. BoundingBox.prototype._update = function (world) {
  18370. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18371. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18372. for (var index = 0; index < this.vectors.length; index++) {
  18373. var v = this.vectorsWorld[index];
  18374. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18375. if (v.x < this.minimumWorld.x)
  18376. this.minimumWorld.x = v.x;
  18377. if (v.y < this.minimumWorld.y)
  18378. this.minimumWorld.y = v.y;
  18379. if (v.z < this.minimumWorld.z)
  18380. this.minimumWorld.z = v.z;
  18381. if (v.x > this.maximumWorld.x)
  18382. this.maximumWorld.x = v.x;
  18383. if (v.y > this.maximumWorld.y)
  18384. this.maximumWorld.y = v.y;
  18385. if (v.z > this.maximumWorld.z)
  18386. this.maximumWorld.z = v.z;
  18387. }
  18388. // Extend
  18389. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18390. this.extendSizeWorld.scaleInPlace(0.5);
  18391. // OBB
  18392. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18393. this.centerWorld.scaleInPlace(0.5);
  18394. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18395. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18396. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18397. this._worldMatrix = world;
  18398. };
  18399. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18400. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18401. };
  18402. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18403. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18404. };
  18405. BoundingBox.prototype.intersectsPoint = function (point) {
  18406. var delta = -BABYLON.Epsilon;
  18407. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18408. return false;
  18409. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18410. return false;
  18411. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18412. return false;
  18413. return true;
  18414. };
  18415. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18416. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18417. };
  18418. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18419. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18420. return false;
  18421. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18422. return false;
  18423. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18424. return false;
  18425. return true;
  18426. };
  18427. // Statics
  18428. BoundingBox.Intersects = function (box0, box1) {
  18429. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18430. return false;
  18431. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18432. return false;
  18433. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18434. return false;
  18435. return true;
  18436. };
  18437. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18438. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18439. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18440. return (num <= (sphereRadius * sphereRadius));
  18441. };
  18442. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18443. for (var p = 0; p < 6; p++) {
  18444. for (var i = 0; i < 8; i++) {
  18445. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18446. return false;
  18447. }
  18448. }
  18449. }
  18450. return true;
  18451. };
  18452. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18453. for (var p = 0; p < 6; p++) {
  18454. var inCount = 8;
  18455. for (var i = 0; i < 8; i++) {
  18456. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18457. --inCount;
  18458. }
  18459. else {
  18460. break;
  18461. }
  18462. }
  18463. if (inCount === 0)
  18464. return false;
  18465. }
  18466. return true;
  18467. };
  18468. return BoundingBox;
  18469. }());
  18470. BABYLON.BoundingBox = BoundingBox;
  18471. })(BABYLON || (BABYLON = {}));
  18472. //# sourceMappingURL=babylon.boundingBox.js.map
  18473. var BABYLON;
  18474. (function (BABYLON) {
  18475. var computeBoxExtents = function (axis, box) {
  18476. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18477. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18478. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18479. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18480. var r = r0 + r1 + r2;
  18481. return {
  18482. min: p - r,
  18483. max: p + r
  18484. };
  18485. };
  18486. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18487. var axisOverlap = function (axis, box0, box1) {
  18488. var result0 = computeBoxExtents(axis, box0);
  18489. var result1 = computeBoxExtents(axis, box1);
  18490. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18491. };
  18492. var BoundingInfo = /** @class */ (function () {
  18493. function BoundingInfo(minimum, maximum) {
  18494. this.minimum = minimum;
  18495. this.maximum = maximum;
  18496. this._isLocked = false;
  18497. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18498. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18499. }
  18500. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18501. get: function () {
  18502. return this._isLocked;
  18503. },
  18504. set: function (value) {
  18505. this._isLocked = value;
  18506. },
  18507. enumerable: true,
  18508. configurable: true
  18509. });
  18510. // Methods
  18511. BoundingInfo.prototype.update = function (world) {
  18512. if (this._isLocked) {
  18513. return;
  18514. }
  18515. this.boundingBox._update(world);
  18516. this.boundingSphere._update(world);
  18517. };
  18518. /**
  18519. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18520. * @param center New center of the bounding info
  18521. * @param extend New extend of the bounding info
  18522. */
  18523. BoundingInfo.prototype.centerOn = function (center, extend) {
  18524. this.minimum = center.subtract(extend);
  18525. this.maximum = center.add(extend);
  18526. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18527. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18528. return this;
  18529. };
  18530. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18531. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18532. return false;
  18533. return this.boundingBox.isInFrustum(frustumPlanes);
  18534. };
  18535. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18536. /**
  18537. * Gets the world distance between the min and max points of the bounding box
  18538. */
  18539. get: function () {
  18540. var boundingBox = this.boundingBox;
  18541. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18542. return size.length();
  18543. },
  18544. enumerable: true,
  18545. configurable: true
  18546. });
  18547. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18548. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18549. };
  18550. BoundingInfo.prototype._checkCollision = function (collider) {
  18551. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18552. };
  18553. BoundingInfo.prototype.intersectsPoint = function (point) {
  18554. if (!this.boundingSphere.centerWorld) {
  18555. return false;
  18556. }
  18557. if (!this.boundingSphere.intersectsPoint(point)) {
  18558. return false;
  18559. }
  18560. if (!this.boundingBox.intersectsPoint(point)) {
  18561. return false;
  18562. }
  18563. return true;
  18564. };
  18565. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18566. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18567. return false;
  18568. }
  18569. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18570. return false;
  18571. }
  18572. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18573. return false;
  18574. }
  18575. if (!precise) {
  18576. return true;
  18577. }
  18578. var box0 = this.boundingBox;
  18579. var box1 = boundingInfo.boundingBox;
  18580. if (!axisOverlap(box0.directions[0], box0, box1))
  18581. return false;
  18582. if (!axisOverlap(box0.directions[1], box0, box1))
  18583. return false;
  18584. if (!axisOverlap(box0.directions[2], box0, box1))
  18585. return false;
  18586. if (!axisOverlap(box1.directions[0], box0, box1))
  18587. return false;
  18588. if (!axisOverlap(box1.directions[1], box0, box1))
  18589. return false;
  18590. if (!axisOverlap(box1.directions[2], box0, box1))
  18591. return false;
  18592. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18593. return false;
  18594. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18595. return false;
  18596. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18597. return false;
  18598. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18599. return false;
  18600. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18601. return false;
  18602. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18603. return false;
  18604. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18605. return false;
  18606. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18607. return false;
  18608. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18609. return false;
  18610. return true;
  18611. };
  18612. return BoundingInfo;
  18613. }());
  18614. BABYLON.BoundingInfo = BoundingInfo;
  18615. })(BABYLON || (BABYLON = {}));
  18616. //# sourceMappingURL=babylon.boundingInfo.js.map
  18617. var BABYLON;
  18618. (function (BABYLON) {
  18619. var TransformNode = /** @class */ (function (_super) {
  18620. __extends(TransformNode, _super);
  18621. function TransformNode(name, scene, isPure) {
  18622. if (scene === void 0) { scene = null; }
  18623. if (isPure === void 0) { isPure = true; }
  18624. var _this = _super.call(this, name, scene) || this;
  18625. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18626. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18627. _this._up = new BABYLON.Vector3(0, 1, 0);
  18628. _this._right = new BABYLON.Vector3(1, 0, 0);
  18629. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18630. // Properties
  18631. _this._rotation = BABYLON.Vector3.Zero();
  18632. _this._scaling = BABYLON.Vector3.One();
  18633. _this._isDirty = false;
  18634. /**
  18635. * Set the billboard mode. Default is 0.
  18636. *
  18637. * | Value | Type | Description |
  18638. * | --- | --- | --- |
  18639. * | 0 | BILLBOARDMODE_NONE | |
  18640. * | 1 | BILLBOARDMODE_X | |
  18641. * | 2 | BILLBOARDMODE_Y | |
  18642. * | 4 | BILLBOARDMODE_Z | |
  18643. * | 7 | BILLBOARDMODE_ALL | |
  18644. *
  18645. */
  18646. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18647. _this.scalingDeterminant = 1;
  18648. _this.infiniteDistance = false;
  18649. /**
  18650. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18651. * By default the system will update normals to compensate
  18652. */
  18653. _this.ignoreNonUniformScaling = false;
  18654. _this.position = BABYLON.Vector3.Zero();
  18655. _this._localWorld = BABYLON.Matrix.Zero();
  18656. _this._worldMatrix = BABYLON.Matrix.Zero();
  18657. _this._worldMatrixDeterminant = 0;
  18658. _this._absolutePosition = BABYLON.Vector3.Zero();
  18659. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18660. _this._postMultiplyPivotMatrix = false;
  18661. _this._isWorldMatrixFrozen = false;
  18662. /**
  18663. * An event triggered after the world matrix is updated
  18664. */
  18665. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18666. _this._nonUniformScaling = false;
  18667. if (isPure) {
  18668. _this.getScene().addTransformNode(_this);
  18669. }
  18670. return _this;
  18671. }
  18672. /**
  18673. * Gets a string idenfifying the name of the class
  18674. * @returns "TransformNode" string
  18675. */
  18676. TransformNode.prototype.getClassName = function () {
  18677. return "TransformNode";
  18678. };
  18679. Object.defineProperty(TransformNode.prototype, "rotation", {
  18680. /**
  18681. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18682. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18683. * Default : (0.0, 0.0, 0.0)
  18684. */
  18685. get: function () {
  18686. return this._rotation;
  18687. },
  18688. set: function (newRotation) {
  18689. this._rotation = newRotation;
  18690. },
  18691. enumerable: true,
  18692. configurable: true
  18693. });
  18694. Object.defineProperty(TransformNode.prototype, "scaling", {
  18695. /**
  18696. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18697. * Default : (1.0, 1.0, 1.0)
  18698. */
  18699. get: function () {
  18700. return this._scaling;
  18701. },
  18702. /**
  18703. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18704. * Default : (1.0, 1.0, 1.0)
  18705. */
  18706. set: function (newScaling) {
  18707. this._scaling = newScaling;
  18708. },
  18709. enumerable: true,
  18710. configurable: true
  18711. });
  18712. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18713. /**
  18714. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18715. * It's null by default.
  18716. * 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)
  18717. */
  18718. get: function () {
  18719. return this._rotationQuaternion;
  18720. },
  18721. set: function (quaternion) {
  18722. this._rotationQuaternion = quaternion;
  18723. //reset the rotation vector.
  18724. if (quaternion && this.rotation.length()) {
  18725. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18726. }
  18727. },
  18728. enumerable: true,
  18729. configurable: true
  18730. });
  18731. Object.defineProperty(TransformNode.prototype, "forward", {
  18732. /**
  18733. * The forward direction of that transform in world space.
  18734. */
  18735. get: function () {
  18736. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18737. },
  18738. enumerable: true,
  18739. configurable: true
  18740. });
  18741. Object.defineProperty(TransformNode.prototype, "up", {
  18742. /**
  18743. * The up direction of that transform in world space.
  18744. */
  18745. get: function () {
  18746. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(TransformNode.prototype, "right", {
  18752. /**
  18753. * The right direction of that transform in world space.
  18754. */
  18755. get: function () {
  18756. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18757. },
  18758. enumerable: true,
  18759. configurable: true
  18760. });
  18761. /**
  18762. * Returns the latest update of the World matrix
  18763. * Returns a Matrix.
  18764. */
  18765. TransformNode.prototype.getWorldMatrix = function () {
  18766. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18767. this.computeWorldMatrix();
  18768. }
  18769. return this._worldMatrix;
  18770. };
  18771. /** @hidden */
  18772. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18773. return this._worldMatrixDeterminant;
  18774. };
  18775. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18776. /**
  18777. * Returns directly the latest state of the mesh World matrix.
  18778. * A Matrix is returned.
  18779. */
  18780. get: function () {
  18781. return this._worldMatrix;
  18782. },
  18783. enumerable: true,
  18784. configurable: true
  18785. });
  18786. /**
  18787. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18788. * Returns the TransformNode.
  18789. */
  18790. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18791. this._poseMatrix.copyFrom(matrix);
  18792. return this;
  18793. };
  18794. /**
  18795. * Returns the mesh Pose matrix.
  18796. * Returned object : Matrix
  18797. */
  18798. TransformNode.prototype.getPoseMatrix = function () {
  18799. return this._poseMatrix;
  18800. };
  18801. TransformNode.prototype._isSynchronized = function () {
  18802. if (this._isDirty) {
  18803. return false;
  18804. }
  18805. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18806. return false;
  18807. if (this._cache.pivotMatrixUpdated) {
  18808. return false;
  18809. }
  18810. if (this.infiniteDistance) {
  18811. return false;
  18812. }
  18813. if (!this._cache.position.equals(this.position))
  18814. return false;
  18815. if (this.rotationQuaternion) {
  18816. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18817. return false;
  18818. }
  18819. if (!this._cache.rotation.equals(this.rotation))
  18820. return false;
  18821. if (!this._cache.scaling.equals(this.scaling))
  18822. return false;
  18823. return true;
  18824. };
  18825. TransformNode.prototype._initCache = function () {
  18826. _super.prototype._initCache.call(this);
  18827. this._cache.localMatrixUpdated = false;
  18828. this._cache.position = BABYLON.Vector3.Zero();
  18829. this._cache.scaling = BABYLON.Vector3.Zero();
  18830. this._cache.rotation = BABYLON.Vector3.Zero();
  18831. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18832. this._cache.billboardMode = -1;
  18833. };
  18834. TransformNode.prototype.markAsDirty = function (property) {
  18835. if (property === "rotation") {
  18836. this.rotationQuaternion = null;
  18837. }
  18838. this._currentRenderId = Number.MAX_VALUE;
  18839. this._isDirty = true;
  18840. return this;
  18841. };
  18842. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18843. /**
  18844. * Returns the current mesh absolute position.
  18845. * Retuns a Vector3.
  18846. */
  18847. get: function () {
  18848. return this._absolutePosition;
  18849. },
  18850. enumerable: true,
  18851. configurable: true
  18852. });
  18853. /**
  18854. * Sets a new matrix to apply before all other transformation
  18855. * @param matrix defines the transform matrix
  18856. * @returns the current TransformNode
  18857. */
  18858. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18859. return this.setPivotMatrix(matrix, false);
  18860. };
  18861. /**
  18862. * Sets a new pivot matrix to the current node
  18863. * @param matrix defines the new pivot matrix to use
  18864. * @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
  18865. * @returns the current TransformNode
  18866. */
  18867. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18868. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18869. this._pivotMatrix = matrix.clone();
  18870. this._cache.pivotMatrixUpdated = true;
  18871. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18872. if (this._postMultiplyPivotMatrix) {
  18873. if (!this._pivotMatrixInverse) {
  18874. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18875. }
  18876. else {
  18877. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18878. }
  18879. }
  18880. return this;
  18881. };
  18882. /**
  18883. * Returns the mesh pivot matrix.
  18884. * Default : Identity.
  18885. * A Matrix is returned.
  18886. */
  18887. TransformNode.prototype.getPivotMatrix = function () {
  18888. return this._pivotMatrix;
  18889. };
  18890. /**
  18891. * Prevents the World matrix to be computed any longer.
  18892. * Returns the TransformNode.
  18893. */
  18894. TransformNode.prototype.freezeWorldMatrix = function () {
  18895. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18896. this.computeWorldMatrix(true);
  18897. this._isWorldMatrixFrozen = true;
  18898. return this;
  18899. };
  18900. /**
  18901. * Allows back the World matrix computation.
  18902. * Returns the TransformNode.
  18903. */
  18904. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18905. this._isWorldMatrixFrozen = false;
  18906. this.computeWorldMatrix(true);
  18907. return this;
  18908. };
  18909. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18910. /**
  18911. * True if the World matrix has been frozen.
  18912. * Returns a boolean.
  18913. */
  18914. get: function () {
  18915. return this._isWorldMatrixFrozen;
  18916. },
  18917. enumerable: true,
  18918. configurable: true
  18919. });
  18920. /**
  18921. * Retuns the mesh absolute position in the World.
  18922. * Returns a Vector3.
  18923. */
  18924. TransformNode.prototype.getAbsolutePosition = function () {
  18925. this.computeWorldMatrix();
  18926. return this._absolutePosition;
  18927. };
  18928. /**
  18929. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18930. * Returns the TransformNode.
  18931. */
  18932. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18933. if (!absolutePosition) {
  18934. return this;
  18935. }
  18936. var absolutePositionX;
  18937. var absolutePositionY;
  18938. var absolutePositionZ;
  18939. if (absolutePosition.x === undefined) {
  18940. if (arguments.length < 3) {
  18941. return this;
  18942. }
  18943. absolutePositionX = arguments[0];
  18944. absolutePositionY = arguments[1];
  18945. absolutePositionZ = arguments[2];
  18946. }
  18947. else {
  18948. absolutePositionX = absolutePosition.x;
  18949. absolutePositionY = absolutePosition.y;
  18950. absolutePositionZ = absolutePosition.z;
  18951. }
  18952. if (this.parent) {
  18953. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18954. invertParentWorldMatrix.invert();
  18955. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18956. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18957. }
  18958. else {
  18959. this.position.x = absolutePositionX;
  18960. this.position.y = absolutePositionY;
  18961. this.position.z = absolutePositionZ;
  18962. }
  18963. return this;
  18964. };
  18965. /**
  18966. * Sets the mesh position in its local space.
  18967. * Returns the TransformNode.
  18968. */
  18969. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18970. this.computeWorldMatrix();
  18971. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18972. return this;
  18973. };
  18974. /**
  18975. * Returns the mesh position in the local space from the current World matrix values.
  18976. * Returns a new Vector3.
  18977. */
  18978. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18979. this.computeWorldMatrix();
  18980. var invLocalWorldMatrix = this._localWorld.clone();
  18981. invLocalWorldMatrix.invert();
  18982. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18983. };
  18984. /**
  18985. * Translates the mesh along the passed Vector3 in its local space.
  18986. * Returns the TransformNode.
  18987. */
  18988. TransformNode.prototype.locallyTranslate = function (vector3) {
  18989. this.computeWorldMatrix(true);
  18990. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18991. return this;
  18992. };
  18993. /**
  18994. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18995. * @param targetPoint the position (must be in same space as current mesh) to look at
  18996. * @param yawCor optional yaw (y-axis) correction in radians
  18997. * @param pitchCor optional pitch (x-axis) correction in radians
  18998. * @param rollCor optional roll (z-axis) correction in radians
  18999. * @param space the choosen space of the target
  19000. * @returns the TransformNode.
  19001. */
  19002. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19003. if (yawCor === void 0) { yawCor = 0; }
  19004. if (pitchCor === void 0) { pitchCor = 0; }
  19005. if (rollCor === void 0) { rollCor = 0; }
  19006. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19007. var dv = TransformNode._lookAtVectorCache;
  19008. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19009. targetPoint.subtractToRef(pos, dv);
  19010. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19011. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19012. var pitch = Math.atan2(dv.y, len);
  19013. if (this.rotationQuaternion) {
  19014. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19015. }
  19016. else {
  19017. this.rotation.x = pitch + pitchCor;
  19018. this.rotation.y = yaw + yawCor;
  19019. this.rotation.z = rollCor;
  19020. }
  19021. return this;
  19022. };
  19023. /**
  19024. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19025. * This Vector3 is expressed in the World space.
  19026. */
  19027. TransformNode.prototype.getDirection = function (localAxis) {
  19028. var result = BABYLON.Vector3.Zero();
  19029. this.getDirectionToRef(localAxis, result);
  19030. return result;
  19031. };
  19032. /**
  19033. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19034. * localAxis is expressed in the mesh local space.
  19035. * result is computed in the Wordl space from the mesh World matrix.
  19036. * Returns the TransformNode.
  19037. */
  19038. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19039. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19040. return this;
  19041. };
  19042. /**
  19043. * Sets a new pivot point to the current node
  19044. * @param point defines the new pivot point to use
  19045. * @param space defines if the point is in world or local space (local by default)
  19046. * @returns the current TransformNode
  19047. */
  19048. TransformNode.prototype.setPivotPoint = function (point, space) {
  19049. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19050. if (this.getScene().getRenderId() == 0) {
  19051. this.computeWorldMatrix(true);
  19052. }
  19053. var wm = this.getWorldMatrix();
  19054. if (space == BABYLON.Space.WORLD) {
  19055. var tmat = BABYLON.Tmp.Matrix[0];
  19056. wm.invertToRef(tmat);
  19057. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19058. }
  19059. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19060. };
  19061. /**
  19062. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19063. */
  19064. TransformNode.prototype.getPivotPoint = function () {
  19065. var point = BABYLON.Vector3.Zero();
  19066. this.getPivotPointToRef(point);
  19067. return point;
  19068. };
  19069. /**
  19070. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19071. * Returns the TransformNode.
  19072. */
  19073. TransformNode.prototype.getPivotPointToRef = function (result) {
  19074. result.x = -this._pivotMatrix.m[12];
  19075. result.y = -this._pivotMatrix.m[13];
  19076. result.z = -this._pivotMatrix.m[14];
  19077. return this;
  19078. };
  19079. /**
  19080. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19081. */
  19082. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19083. var point = BABYLON.Vector3.Zero();
  19084. this.getAbsolutePivotPointToRef(point);
  19085. return point;
  19086. };
  19087. /**
  19088. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19089. * Returns the TransformNode.
  19090. */
  19091. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19092. result.x = this._pivotMatrix.m[12];
  19093. result.y = this._pivotMatrix.m[13];
  19094. result.z = this._pivotMatrix.m[14];
  19095. this.getPivotPointToRef(result);
  19096. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19097. return this;
  19098. };
  19099. /**
  19100. * Defines the passed node as the parent of the current node.
  19101. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19102. * Returns the TransformNode.
  19103. */
  19104. TransformNode.prototype.setParent = function (node) {
  19105. if (!node && !this.parent) {
  19106. return this;
  19107. }
  19108. if (!node) {
  19109. var rotation = BABYLON.Tmp.Quaternion[0];
  19110. var position = BABYLON.Tmp.Vector3[0];
  19111. var scale = BABYLON.Tmp.Vector3[1];
  19112. if (this.parent && this.parent.computeWorldMatrix) {
  19113. this.parent.computeWorldMatrix(true);
  19114. }
  19115. this.computeWorldMatrix(true);
  19116. this.getWorldMatrix().decompose(scale, rotation, position);
  19117. if (this.rotationQuaternion) {
  19118. this.rotationQuaternion.copyFrom(rotation);
  19119. }
  19120. else {
  19121. rotation.toEulerAnglesToRef(this.rotation);
  19122. }
  19123. this.scaling.x = scale.x;
  19124. this.scaling.y = scale.y;
  19125. this.scaling.z = scale.z;
  19126. this.position.x = position.x;
  19127. this.position.y = position.y;
  19128. this.position.z = position.z;
  19129. }
  19130. else {
  19131. var rotation = BABYLON.Tmp.Quaternion[0];
  19132. var position = BABYLON.Tmp.Vector3[0];
  19133. var scale = BABYLON.Tmp.Vector3[1];
  19134. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19135. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19136. this.computeWorldMatrix(true);
  19137. node.computeWorldMatrix(true);
  19138. node.getWorldMatrix().invertToRef(invParentMatrix);
  19139. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19140. diffMatrix.decompose(scale, rotation, position);
  19141. if (this.rotationQuaternion) {
  19142. this.rotationQuaternion.copyFrom(rotation);
  19143. }
  19144. else {
  19145. rotation.toEulerAnglesToRef(this.rotation);
  19146. }
  19147. this.position.x = position.x;
  19148. this.position.y = position.y;
  19149. this.position.z = position.z;
  19150. this.scaling.x = scale.x;
  19151. this.scaling.y = scale.y;
  19152. this.scaling.z = scale.z;
  19153. }
  19154. this.parent = node;
  19155. return this;
  19156. };
  19157. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19158. get: function () {
  19159. return this._nonUniformScaling;
  19160. },
  19161. enumerable: true,
  19162. configurable: true
  19163. });
  19164. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19165. if (this._nonUniformScaling === value) {
  19166. return false;
  19167. }
  19168. this._nonUniformScaling = value;
  19169. return true;
  19170. };
  19171. /**
  19172. * Attach the current TransformNode to another TransformNode associated with a bone
  19173. * @param bone Bone affecting the TransformNode
  19174. * @param affectedTransformNode TransformNode associated with the bone
  19175. */
  19176. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19177. this._transformToBoneReferal = affectedTransformNode;
  19178. this.parent = bone;
  19179. if (bone.getWorldMatrix().determinant() < 0) {
  19180. this.scalingDeterminant *= -1;
  19181. }
  19182. return this;
  19183. };
  19184. TransformNode.prototype.detachFromBone = function () {
  19185. if (!this.parent) {
  19186. return this;
  19187. }
  19188. if (this.parent.getWorldMatrix().determinant() < 0) {
  19189. this.scalingDeterminant *= -1;
  19190. }
  19191. this._transformToBoneReferal = null;
  19192. this.parent = null;
  19193. return this;
  19194. };
  19195. /**
  19196. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19197. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19198. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19199. * The passed axis is also normalized.
  19200. * Returns the TransformNode.
  19201. */
  19202. TransformNode.prototype.rotate = function (axis, amount, space) {
  19203. axis.normalize();
  19204. if (!this.rotationQuaternion) {
  19205. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19206. this.rotation = BABYLON.Vector3.Zero();
  19207. }
  19208. var rotationQuaternion;
  19209. if (!space || space === BABYLON.Space.LOCAL) {
  19210. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19211. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19212. }
  19213. else {
  19214. if (this.parent) {
  19215. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19216. invertParentWorldMatrix.invert();
  19217. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19218. }
  19219. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19220. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19221. }
  19222. return this;
  19223. };
  19224. /**
  19225. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19226. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19227. * The passed axis is also normalized.
  19228. * Returns the TransformNode.
  19229. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19230. */
  19231. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19232. axis.normalize();
  19233. if (!this.rotationQuaternion) {
  19234. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19235. this.rotation.copyFromFloats(0, 0, 0);
  19236. }
  19237. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19238. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19239. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19240. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19241. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19242. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19243. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19244. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19245. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19246. return this;
  19247. };
  19248. /**
  19249. * Translates the mesh along the axis vector for the passed distance in the given space.
  19250. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19251. * Returns the TransformNode.
  19252. */
  19253. TransformNode.prototype.translate = function (axis, distance, space) {
  19254. var displacementVector = axis.scale(distance);
  19255. if (!space || space === BABYLON.Space.LOCAL) {
  19256. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19257. this.setPositionWithLocalVector(tempV3);
  19258. }
  19259. else {
  19260. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19261. }
  19262. return this;
  19263. };
  19264. /**
  19265. * Adds a rotation step to the mesh current rotation.
  19266. * x, y, z are Euler angles expressed in radians.
  19267. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19268. * This means this rotation is made in the mesh local space only.
  19269. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19270. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19271. * ```javascript
  19272. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19273. * ```
  19274. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19275. * 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.
  19276. * Returns the TransformNode.
  19277. */
  19278. TransformNode.prototype.addRotation = function (x, y, z) {
  19279. var rotationQuaternion;
  19280. if (this.rotationQuaternion) {
  19281. rotationQuaternion = this.rotationQuaternion;
  19282. }
  19283. else {
  19284. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19285. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19286. }
  19287. var accumulation = BABYLON.Tmp.Quaternion[0];
  19288. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19289. rotationQuaternion.multiplyInPlace(accumulation);
  19290. if (!this.rotationQuaternion) {
  19291. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19292. }
  19293. return this;
  19294. };
  19295. /**
  19296. * Computes the mesh World matrix and returns it.
  19297. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19298. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19299. * If the parameter `force`is set to `true`, the actual computation is done.
  19300. * Returns the mesh World Matrix.
  19301. */
  19302. TransformNode.prototype.computeWorldMatrix = function (force) {
  19303. if (this._isWorldMatrixFrozen) {
  19304. return this._worldMatrix;
  19305. }
  19306. if (!force && this.isSynchronized(true)) {
  19307. this._currentRenderId = this.getScene().getRenderId();
  19308. return this._worldMatrix;
  19309. }
  19310. this._cache.position.copyFrom(this.position);
  19311. this._cache.scaling.copyFrom(this.scaling);
  19312. this._cache.pivotMatrixUpdated = false;
  19313. this._cache.billboardMode = this.billboardMode;
  19314. this._currentRenderId = this.getScene().getRenderId();
  19315. this._childRenderId = this.getScene().getRenderId();
  19316. this._isDirty = false;
  19317. // Scaling
  19318. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19319. // Rotation
  19320. //rotate, if quaternion is set and rotation was used
  19321. if (this.rotationQuaternion) {
  19322. var len = this.rotation.length();
  19323. if (len) {
  19324. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19325. this.rotation.copyFromFloats(0, 0, 0);
  19326. }
  19327. }
  19328. if (this.rotationQuaternion) {
  19329. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19330. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19331. }
  19332. else {
  19333. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19334. this._cache.rotation.copyFrom(this.rotation);
  19335. }
  19336. // Translation
  19337. var camera = this.getScene().activeCamera;
  19338. if (this.infiniteDistance && !this.parent && camera) {
  19339. var cameraWorldMatrix = camera.getWorldMatrix();
  19340. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19341. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19342. }
  19343. else {
  19344. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19345. }
  19346. // Composing transformations
  19347. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19348. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19349. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19350. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19351. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19352. // Need to decompose each rotation here
  19353. var currentPosition = BABYLON.Tmp.Vector3[3];
  19354. if (this.parent && this.parent.getWorldMatrix) {
  19355. if (this._transformToBoneReferal) {
  19356. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19357. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19358. }
  19359. else {
  19360. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19361. }
  19362. }
  19363. else {
  19364. currentPosition.copyFrom(this.position);
  19365. }
  19366. currentPosition.subtractInPlace(camera.globalPosition);
  19367. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19368. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19369. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19370. }
  19371. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19372. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19373. }
  19374. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19375. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19376. }
  19377. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19378. }
  19379. else {
  19380. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19381. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19382. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19383. }
  19384. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19385. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19386. }
  19387. // Local world
  19388. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19389. // Parent
  19390. if (this.parent && this.parent.getWorldMatrix) {
  19391. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19392. if (this._transformToBoneReferal) {
  19393. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19394. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19395. }
  19396. else {
  19397. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19398. }
  19399. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19400. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19401. this._worldMatrix.copyFrom(this._localWorld);
  19402. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19403. }
  19404. else {
  19405. if (this._transformToBoneReferal) {
  19406. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19407. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19408. }
  19409. else {
  19410. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19411. }
  19412. }
  19413. this._markSyncedWithParent();
  19414. }
  19415. else {
  19416. this._worldMatrix.copyFrom(this._localWorld);
  19417. }
  19418. // Post multiply inverse of pivotMatrix
  19419. if (this._postMultiplyPivotMatrix) {
  19420. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19421. }
  19422. // Normal matrix
  19423. if (!this.ignoreNonUniformScaling) {
  19424. if (this.scaling.isNonUniform) {
  19425. this._updateNonUniformScalingState(true);
  19426. }
  19427. else if (this.parent && this.parent._nonUniformScaling) {
  19428. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19429. }
  19430. else {
  19431. this._updateNonUniformScalingState(false);
  19432. }
  19433. }
  19434. else {
  19435. this._updateNonUniformScalingState(false);
  19436. }
  19437. this._afterComputeWorldMatrix();
  19438. // Absolute position
  19439. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19440. // Callbacks
  19441. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19442. if (!this._poseMatrix) {
  19443. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19444. }
  19445. // Cache the determinant
  19446. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19447. return this._worldMatrix;
  19448. };
  19449. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19450. };
  19451. /**
  19452. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19453. * @param func: callback function to add
  19454. *
  19455. * Returns the TransformNode.
  19456. */
  19457. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19458. this.onAfterWorldMatrixUpdateObservable.add(func);
  19459. return this;
  19460. };
  19461. /**
  19462. * Removes a registered callback function.
  19463. * Returns the TransformNode.
  19464. */
  19465. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19466. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19467. return this;
  19468. };
  19469. /**
  19470. * Clone the current transform node
  19471. * Returns the new transform node
  19472. * @param name Name of the new clone
  19473. * @param newParent New parent for the clone
  19474. * @param doNotCloneChildren Do not clone children hierarchy
  19475. */
  19476. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19477. var _this = this;
  19478. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19479. result.name = name;
  19480. result.id = name;
  19481. if (newParent) {
  19482. result.parent = newParent;
  19483. }
  19484. if (!doNotCloneChildren) {
  19485. // Children
  19486. var directDescendants = this.getDescendants(true);
  19487. for (var index = 0; index < directDescendants.length; index++) {
  19488. var child = directDescendants[index];
  19489. if (child.clone) {
  19490. child.clone(name + "." + child.name, result);
  19491. }
  19492. }
  19493. }
  19494. return result;
  19495. };
  19496. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19497. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19498. serializationObject.type = this.getClassName();
  19499. // Parent
  19500. if (this.parent) {
  19501. serializationObject.parentId = this.parent.id;
  19502. }
  19503. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19504. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19505. }
  19506. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19507. serializationObject.isEnabled = this.isEnabled();
  19508. // Parent
  19509. if (this.parent) {
  19510. serializationObject.parentId = this.parent.id;
  19511. }
  19512. return serializationObject;
  19513. };
  19514. // Statics
  19515. /**
  19516. * Returns a new TransformNode object parsed from the source provided.
  19517. * The parameter `parsedMesh` is the source.
  19518. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19519. */
  19520. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19521. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19522. if (BABYLON.Tags) {
  19523. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19524. }
  19525. if (parsedTransformNode.localMatrix) {
  19526. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19527. }
  19528. else if (parsedTransformNode.pivotMatrix) {
  19529. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19530. }
  19531. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19532. // Parent
  19533. if (parsedTransformNode.parentId) {
  19534. transformNode._waitingParentId = parsedTransformNode.parentId;
  19535. }
  19536. return transformNode;
  19537. };
  19538. /**
  19539. * Releases resources associated with this transform node.
  19540. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19541. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19542. */
  19543. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19544. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19545. // Animations
  19546. this.getScene().stopAnimation(this);
  19547. // Remove from scene
  19548. this.getScene().removeTransformNode(this);
  19549. this.onAfterWorldMatrixUpdateObservable.clear();
  19550. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19551. };
  19552. // Statics
  19553. TransformNode.BILLBOARDMODE_NONE = 0;
  19554. TransformNode.BILLBOARDMODE_X = 1;
  19555. TransformNode.BILLBOARDMODE_Y = 2;
  19556. TransformNode.BILLBOARDMODE_Z = 4;
  19557. TransformNode.BILLBOARDMODE_ALL = 7;
  19558. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19559. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19560. __decorate([
  19561. BABYLON.serializeAsVector3()
  19562. ], TransformNode.prototype, "_rotation", void 0);
  19563. __decorate([
  19564. BABYLON.serializeAsQuaternion()
  19565. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19566. __decorate([
  19567. BABYLON.serializeAsVector3()
  19568. ], TransformNode.prototype, "_scaling", void 0);
  19569. __decorate([
  19570. BABYLON.serialize()
  19571. ], TransformNode.prototype, "billboardMode", void 0);
  19572. __decorate([
  19573. BABYLON.serialize()
  19574. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19575. __decorate([
  19576. BABYLON.serialize()
  19577. ], TransformNode.prototype, "infiniteDistance", void 0);
  19578. __decorate([
  19579. BABYLON.serialize()
  19580. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19581. __decorate([
  19582. BABYLON.serializeAsVector3()
  19583. ], TransformNode.prototype, "position", void 0);
  19584. return TransformNode;
  19585. }(BABYLON.Node));
  19586. BABYLON.TransformNode = TransformNode;
  19587. })(BABYLON || (BABYLON = {}));
  19588. //# sourceMappingURL=babylon.transformNode.js.map
  19589. var BABYLON;
  19590. (function (BABYLON) {
  19591. /**
  19592. * Class used to store all common mesh properties
  19593. */
  19594. var AbstractMesh = /** @class */ (function (_super) {
  19595. __extends(AbstractMesh, _super);
  19596. // Constructor
  19597. /**
  19598. * Creates a new AbstractMesh
  19599. * @param name defines the name of the mesh
  19600. * @param scene defines the hosting scene
  19601. */
  19602. function AbstractMesh(name, scene) {
  19603. if (scene === void 0) { scene = null; }
  19604. var _this = _super.call(this, name, scene, false) || this;
  19605. _this._facetNb = 0; // facet number
  19606. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19607. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19608. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19609. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19610. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19611. _this._subDiv = {
  19612. max: 1,
  19613. X: 1,
  19614. Y: 1,
  19615. Z: 1
  19616. };
  19617. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19618. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19619. // Events
  19620. /**
  19621. * An event triggered when this mesh collides with another one
  19622. */
  19623. _this.onCollideObservable = new BABYLON.Observable();
  19624. /**
  19625. * An event triggered when the collision's position changes
  19626. */
  19627. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19628. /**
  19629. * An event triggered when material is changed
  19630. */
  19631. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19632. // Properties
  19633. /**
  19634. * Gets or sets the orientation for POV movement & rotation
  19635. */
  19636. _this.definedFacingForward = true;
  19637. /**
  19638. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19639. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19640. * * 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.
  19641. * @see http://doc.babylonjs.com/features/occlusionquery
  19642. */
  19643. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19644. /**
  19645. * 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:
  19646. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19647. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19648. * * 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.
  19649. * @see http://doc.babylonjs.com/features/occlusionquery
  19650. */
  19651. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19652. /**
  19653. * 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.
  19654. * The default value is -1 which means don't break the query and wait till the result
  19655. * @see http://doc.babylonjs.com/features/occlusionquery
  19656. */
  19657. _this.occlusionRetryCount = -1;
  19658. _this._occlusionInternalRetryCounter = 0;
  19659. _this._isOccluded = false;
  19660. _this._isOcclusionQueryInProgress = false;
  19661. _this._visibility = 1.0;
  19662. /** Gets or sets the alpha index used to sort transparent meshes
  19663. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19664. */
  19665. _this.alphaIndex = Number.MAX_VALUE;
  19666. /**
  19667. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19668. */
  19669. _this.isVisible = true;
  19670. /**
  19671. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19672. */
  19673. _this.isPickable = true;
  19674. /**
  19675. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19676. */
  19677. _this.showBoundingBox = false;
  19678. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19679. _this.showSubMeshesBoundingBox = false;
  19680. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19681. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19682. */
  19683. _this.isBlocker = false;
  19684. /**
  19685. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19686. */
  19687. _this.enablePointerMoveEvents = false;
  19688. /**
  19689. * Specifies the rendering group id for this mesh (0 by default)
  19690. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19691. */
  19692. _this.renderingGroupId = 0;
  19693. _this._receiveShadows = false;
  19694. /**
  19695. * Gets or sets a boolean indicating if the outline must be rendered as well
  19696. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19697. */
  19698. _this.renderOutline = false;
  19699. /** Defines color to use when rendering outline */
  19700. _this.outlineColor = BABYLON.Color3.Red();
  19701. /** Define width to use when rendering outline */
  19702. _this.outlineWidth = 0.02;
  19703. /**
  19704. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19705. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19706. */
  19707. _this.renderOverlay = false;
  19708. /** Defines color to use when rendering overlay */
  19709. _this.overlayColor = BABYLON.Color3.Red();
  19710. /** Defines alpha to use when rendering overlay */
  19711. _this.overlayAlpha = 0.5;
  19712. _this._hasVertexAlpha = false;
  19713. _this._useVertexColors = true;
  19714. _this._computeBonesUsingShaders = true;
  19715. _this._numBoneInfluencers = 4;
  19716. _this._applyFog = true;
  19717. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19718. _this.useOctreeForRenderingSelection = true;
  19719. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19720. _this.useOctreeForPicking = true;
  19721. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19722. _this.useOctreeForCollisions = true;
  19723. _this._layerMask = 0x0FFFFFFF;
  19724. /**
  19725. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19726. */
  19727. _this.alwaysSelectAsActiveMesh = false;
  19728. /**
  19729. * Gets or sets the current action manager
  19730. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19731. */
  19732. _this.actionManager = null;
  19733. /**
  19734. * Gets or sets impostor used for physic simulation
  19735. * @see http://doc.babylonjs.com/features/physics_engine
  19736. */
  19737. _this.physicsImpostor = null;
  19738. // Collisions
  19739. _this._checkCollisions = false;
  19740. _this._collisionMask = -1;
  19741. _this._collisionGroup = -1;
  19742. /**
  19743. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19744. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19745. */
  19746. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19747. /**
  19748. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19749. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19750. */
  19751. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19752. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19753. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19754. // Edges
  19755. /**
  19756. * Defines edge width used when edgesRenderer is enabled
  19757. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19758. */
  19759. _this.edgesWidth = 1;
  19760. /**
  19761. * Defines edge color used when edgesRenderer is enabled
  19762. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19763. */
  19764. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19765. // Cache
  19766. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19767. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19768. /** @hidden */
  19769. _this._renderId = 0;
  19770. /** @hidden */
  19771. _this._intersectionsInProgress = new Array();
  19772. /** @hidden */
  19773. _this._unIndexed = false;
  19774. /** @hidden */
  19775. _this._lightSources = new Array();
  19776. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19777. if (collidedMesh === void 0) { collidedMesh = null; }
  19778. //TODO move this to the collision coordinator!
  19779. if (_this.getScene().workerCollisions)
  19780. newPosition.multiplyInPlace(_this._collider._radius);
  19781. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19782. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19783. _this.position.addInPlace(_this._diffPositionForCollisions);
  19784. }
  19785. if (collidedMesh) {
  19786. _this.onCollideObservable.notifyObservers(collidedMesh);
  19787. }
  19788. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19789. };
  19790. _this.getScene().addMesh(_this);
  19791. _this._resyncLightSources();
  19792. return _this;
  19793. }
  19794. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19795. /**
  19796. * No billboard
  19797. */
  19798. get: function () {
  19799. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19800. },
  19801. enumerable: true,
  19802. configurable: true
  19803. });
  19804. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19805. /** Billboard on X axis */
  19806. get: function () {
  19807. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19808. },
  19809. enumerable: true,
  19810. configurable: true
  19811. });
  19812. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19813. /** Billboard on Y axis */
  19814. get: function () {
  19815. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19816. },
  19817. enumerable: true,
  19818. configurable: true
  19819. });
  19820. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19821. /** Billboard on Z axis */
  19822. get: function () {
  19823. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19829. /** Billboard on all axes */
  19830. get: function () {
  19831. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19837. /**
  19838. * Gets the number of facets in the mesh
  19839. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19840. */
  19841. get: function () {
  19842. return this._facetNb;
  19843. },
  19844. enumerable: true,
  19845. configurable: true
  19846. });
  19847. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19848. /**
  19849. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19850. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19851. */
  19852. get: function () {
  19853. return this._partitioningSubdivisions;
  19854. },
  19855. set: function (nb) {
  19856. this._partitioningSubdivisions = nb;
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19862. /**
  19863. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19864. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19865. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19866. */
  19867. get: function () {
  19868. return this._partitioningBBoxRatio;
  19869. },
  19870. set: function (ratio) {
  19871. this._partitioningBBoxRatio = ratio;
  19872. },
  19873. enumerable: true,
  19874. configurable: true
  19875. });
  19876. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19877. /**
  19878. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19879. * Works only for updatable meshes.
  19880. * Doesn't work with multi-materials
  19881. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19882. */
  19883. get: function () {
  19884. return this._facetDepthSort;
  19885. },
  19886. set: function (sort) {
  19887. this._facetDepthSort = sort;
  19888. },
  19889. enumerable: true,
  19890. configurable: true
  19891. });
  19892. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19893. /**
  19894. * The location (Vector3) where the facet depth sort must be computed from.
  19895. * By default, the active camera position.
  19896. * Used only when facet depth sort is enabled
  19897. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19898. */
  19899. get: function () {
  19900. return this._facetDepthSortFrom;
  19901. },
  19902. set: function (location) {
  19903. this._facetDepthSortFrom = location;
  19904. },
  19905. enumerable: true,
  19906. configurable: true
  19907. });
  19908. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19909. /**
  19910. * gets a boolean indicating if facetData is enabled
  19911. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19912. */
  19913. get: function () {
  19914. return this._facetDataEnabled;
  19915. },
  19916. enumerable: true,
  19917. configurable: true
  19918. });
  19919. /** @hidden */
  19920. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19921. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19922. return false;
  19923. }
  19924. this._markSubMeshesAsMiscDirty();
  19925. return true;
  19926. };
  19927. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19928. /** Set a function to call when this mesh collides with another one */
  19929. set: function (callback) {
  19930. if (this._onCollideObserver) {
  19931. this.onCollideObservable.remove(this._onCollideObserver);
  19932. }
  19933. this._onCollideObserver = this.onCollideObservable.add(callback);
  19934. },
  19935. enumerable: true,
  19936. configurable: true
  19937. });
  19938. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19939. /** Set a function to call when the collision's position changes */
  19940. set: function (callback) {
  19941. if (this._onCollisionPositionChangeObserver) {
  19942. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19943. }
  19944. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19945. },
  19946. enumerable: true,
  19947. configurable: true
  19948. });
  19949. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19950. /**
  19951. * 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
  19952. * @see http://doc.babylonjs.com/features/occlusionquery
  19953. */
  19954. get: function () {
  19955. return this._isOccluded;
  19956. },
  19957. set: function (value) {
  19958. this._isOccluded = value;
  19959. },
  19960. enumerable: true,
  19961. configurable: true
  19962. });
  19963. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19964. /**
  19965. * Flag to check the progress status of the query
  19966. * @see http://doc.babylonjs.com/features/occlusionquery
  19967. */
  19968. get: function () {
  19969. return this._isOcclusionQueryInProgress;
  19970. },
  19971. enumerable: true,
  19972. configurable: true
  19973. });
  19974. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19975. /**
  19976. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19977. */
  19978. get: function () {
  19979. return this._visibility;
  19980. },
  19981. /**
  19982. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19983. */
  19984. set: function (value) {
  19985. if (this._visibility === value) {
  19986. return;
  19987. }
  19988. this._visibility = value;
  19989. this._markSubMeshesAsMiscDirty();
  19990. },
  19991. enumerable: true,
  19992. configurable: true
  19993. });
  19994. Object.defineProperty(AbstractMesh.prototype, "material", {
  19995. /** Gets or sets current material */
  19996. get: function () {
  19997. return this._material;
  19998. },
  19999. set: function (value) {
  20000. if (this._material === value) {
  20001. return;
  20002. }
  20003. this._material = value;
  20004. if (this.onMaterialChangedObservable.hasObservers) {
  20005. this.onMaterialChangedObservable.notifyObservers(this);
  20006. }
  20007. if (!this.subMeshes) {
  20008. return;
  20009. }
  20010. this._unBindEffect();
  20011. },
  20012. enumerable: true,
  20013. configurable: true
  20014. });
  20015. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20016. /**
  20017. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20018. * @see http://doc.babylonjs.com/babylon101/shadows
  20019. */
  20020. get: function () {
  20021. return this._receiveShadows;
  20022. },
  20023. set: function (value) {
  20024. if (this._receiveShadows === value) {
  20025. return;
  20026. }
  20027. this._receiveShadows = value;
  20028. this._markSubMeshesAsLightDirty();
  20029. },
  20030. enumerable: true,
  20031. configurable: true
  20032. });
  20033. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20034. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20035. get: function () {
  20036. return this._hasVertexAlpha;
  20037. },
  20038. set: function (value) {
  20039. if (this._hasVertexAlpha === value) {
  20040. return;
  20041. }
  20042. this._hasVertexAlpha = value;
  20043. this._markSubMeshesAsAttributesDirty();
  20044. this._markSubMeshesAsMiscDirty();
  20045. },
  20046. enumerable: true,
  20047. configurable: true
  20048. });
  20049. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20050. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  20051. get: function () {
  20052. return this._useVertexColors;
  20053. },
  20054. set: function (value) {
  20055. if (this._useVertexColors === value) {
  20056. return;
  20057. }
  20058. this._useVertexColors = value;
  20059. this._markSubMeshesAsAttributesDirty();
  20060. },
  20061. enumerable: true,
  20062. configurable: true
  20063. });
  20064. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20065. /**
  20066. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20067. */
  20068. get: function () {
  20069. return this._computeBonesUsingShaders;
  20070. },
  20071. set: function (value) {
  20072. if (this._computeBonesUsingShaders === value) {
  20073. return;
  20074. }
  20075. this._computeBonesUsingShaders = value;
  20076. this._markSubMeshesAsAttributesDirty();
  20077. },
  20078. enumerable: true,
  20079. configurable: true
  20080. });
  20081. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20082. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20083. get: function () {
  20084. return this._numBoneInfluencers;
  20085. },
  20086. set: function (value) {
  20087. if (this._numBoneInfluencers === value) {
  20088. return;
  20089. }
  20090. this._numBoneInfluencers = value;
  20091. this._markSubMeshesAsAttributesDirty();
  20092. },
  20093. enumerable: true,
  20094. configurable: true
  20095. });
  20096. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20097. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20098. get: function () {
  20099. return this._applyFog;
  20100. },
  20101. set: function (value) {
  20102. if (this._applyFog === value) {
  20103. return;
  20104. }
  20105. this._applyFog = value;
  20106. this._markSubMeshesAsMiscDirty();
  20107. },
  20108. enumerable: true,
  20109. configurable: true
  20110. });
  20111. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20112. /**
  20113. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20114. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20115. */
  20116. get: function () {
  20117. return this._layerMask;
  20118. },
  20119. set: function (value) {
  20120. if (value === this._layerMask) {
  20121. return;
  20122. }
  20123. this._layerMask = value;
  20124. this._resyncLightSources();
  20125. },
  20126. enumerable: true,
  20127. configurable: true
  20128. });
  20129. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20130. /**
  20131. * Gets or sets a collision mask used to mask collisions (default is -1).
  20132. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20133. */
  20134. get: function () {
  20135. return this._collisionMask;
  20136. },
  20137. set: function (mask) {
  20138. this._collisionMask = !isNaN(mask) ? mask : -1;
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20144. /**
  20145. * Gets or sets the current collision group mask (-1 by default).
  20146. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20147. */
  20148. get: function () {
  20149. return this._collisionGroup;
  20150. },
  20151. set: function (mask) {
  20152. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20153. },
  20154. enumerable: true,
  20155. configurable: true
  20156. });
  20157. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20158. /** @hidden */
  20159. get: function () {
  20160. return null;
  20161. },
  20162. enumerable: true,
  20163. configurable: true
  20164. });
  20165. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20166. get: function () {
  20167. return this._skeleton;
  20168. },
  20169. /**
  20170. * Gets or sets a skeleton to apply skining transformations
  20171. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20172. */
  20173. set: function (value) {
  20174. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20175. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20176. }
  20177. if (value && value.needInitialSkinMatrix) {
  20178. value._registerMeshWithPoseMatrix(this);
  20179. }
  20180. this._skeleton = value;
  20181. if (!this._skeleton) {
  20182. this._bonesTransformMatrices = null;
  20183. }
  20184. this._markSubMeshesAsAttributesDirty();
  20185. },
  20186. enumerable: true,
  20187. configurable: true
  20188. });
  20189. /**
  20190. * Returns the string "AbstractMesh"
  20191. * @returns "AbstractMesh"
  20192. */
  20193. AbstractMesh.prototype.getClassName = function () {
  20194. return "AbstractMesh";
  20195. };
  20196. /**
  20197. * Gets a string representation of the current mesh
  20198. * @param fullDetails defines a boolean indicating if full details must be included
  20199. * @returns a string representation of the current mesh
  20200. */
  20201. AbstractMesh.prototype.toString = function (fullDetails) {
  20202. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20203. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20204. if (this._skeleton) {
  20205. ret += ", skeleton: " + this._skeleton.name;
  20206. }
  20207. if (fullDetails) {
  20208. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20209. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20210. }
  20211. return ret;
  20212. };
  20213. /** @hidden */
  20214. AbstractMesh.prototype._rebuild = function () {
  20215. if (this._occlusionQuery) {
  20216. this._occlusionQuery = null;
  20217. }
  20218. if (this._edgesRenderer) {
  20219. this._edgesRenderer._rebuild();
  20220. }
  20221. if (!this.subMeshes) {
  20222. return;
  20223. }
  20224. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20225. var subMesh = _a[_i];
  20226. subMesh._rebuild();
  20227. }
  20228. };
  20229. /** @hidden */
  20230. AbstractMesh.prototype._resyncLightSources = function () {
  20231. this._lightSources.length = 0;
  20232. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20233. var light = _a[_i];
  20234. if (!light.isEnabled()) {
  20235. continue;
  20236. }
  20237. if (light.canAffectMesh(this)) {
  20238. this._lightSources.push(light);
  20239. }
  20240. }
  20241. this._markSubMeshesAsLightDirty();
  20242. };
  20243. /** @hidden */
  20244. AbstractMesh.prototype._resyncLighSource = function (light) {
  20245. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20246. var index = this._lightSources.indexOf(light);
  20247. if (index === -1) {
  20248. if (!isIn) {
  20249. return;
  20250. }
  20251. this._lightSources.push(light);
  20252. }
  20253. else {
  20254. if (isIn) {
  20255. return;
  20256. }
  20257. this._lightSources.splice(index, 1);
  20258. }
  20259. this._markSubMeshesAsLightDirty();
  20260. };
  20261. /** @hidden */
  20262. AbstractMesh.prototype._unBindEffect = function () {
  20263. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20264. var subMesh = _a[_i];
  20265. subMesh.setEffect(null);
  20266. }
  20267. };
  20268. /** @hidden */
  20269. AbstractMesh.prototype._removeLightSource = function (light) {
  20270. var index = this._lightSources.indexOf(light);
  20271. if (index === -1) {
  20272. return;
  20273. }
  20274. this._lightSources.splice(index, 1);
  20275. this._markSubMeshesAsLightDirty();
  20276. };
  20277. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20278. if (!this.subMeshes) {
  20279. return;
  20280. }
  20281. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20282. var subMesh = _a[_i];
  20283. if (subMesh._materialDefines) {
  20284. func(subMesh._materialDefines);
  20285. }
  20286. }
  20287. };
  20288. /** @hidden */
  20289. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20290. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20291. };
  20292. /** @hidden */
  20293. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20294. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20295. };
  20296. /** @hidden */
  20297. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20298. if (!this.subMeshes) {
  20299. return;
  20300. }
  20301. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20302. var subMesh = _a[_i];
  20303. var material = subMesh.getMaterial();
  20304. if (material) {
  20305. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20306. }
  20307. }
  20308. };
  20309. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20310. /**
  20311. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20312. */
  20313. get: function () {
  20314. return this._scaling;
  20315. },
  20316. set: function (newScaling) {
  20317. this._scaling = newScaling;
  20318. if (this.physicsImpostor) {
  20319. this.physicsImpostor.forceUpdate();
  20320. }
  20321. },
  20322. enumerable: true,
  20323. configurable: true
  20324. });
  20325. // Methods
  20326. /**
  20327. * Disables the mesh edge rendering mode
  20328. * @returns the currentAbstractMesh
  20329. */
  20330. AbstractMesh.prototype.disableEdgesRendering = function () {
  20331. if (this._edgesRenderer) {
  20332. this._edgesRenderer.dispose();
  20333. this._edgesRenderer = null;
  20334. }
  20335. return this;
  20336. };
  20337. /**
  20338. * Enables the edge rendering mode on the mesh.
  20339. * This mode makes the mesh edges visible
  20340. * @param epsilon defines the maximal distance between two angles to detect a face
  20341. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20342. * @returns the currentAbstractMesh
  20343. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20344. */
  20345. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20346. if (epsilon === void 0) { epsilon = 0.95; }
  20347. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20348. this.disableEdgesRendering();
  20349. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20350. return this;
  20351. };
  20352. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20353. /**
  20354. * Gets the edgesRenderer associated with the mesh
  20355. */
  20356. get: function () {
  20357. return this._edgesRenderer;
  20358. },
  20359. enumerable: true,
  20360. configurable: true
  20361. });
  20362. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20363. /**
  20364. * Returns true if the mesh is blocked. Implemented by child classes
  20365. */
  20366. get: function () {
  20367. return false;
  20368. },
  20369. enumerable: true,
  20370. configurable: true
  20371. });
  20372. /**
  20373. * Returns the mesh itself by default. Implemented by child classes
  20374. * @param camera defines the camera to use to pick the right LOD level
  20375. * @returns the currentAbstractMesh
  20376. */
  20377. AbstractMesh.prototype.getLOD = function (camera) {
  20378. return this;
  20379. };
  20380. /**
  20381. * Returns 0 by default. Implemented by child classes
  20382. * @returns an integer
  20383. */
  20384. AbstractMesh.prototype.getTotalVertices = function () {
  20385. return 0;
  20386. };
  20387. /**
  20388. * Returns null by default. Implemented by child classes
  20389. * @returns null
  20390. */
  20391. AbstractMesh.prototype.getIndices = function () {
  20392. return null;
  20393. };
  20394. /**
  20395. * Returns the array of the requested vertex data kind. Implemented by child classes
  20396. * @param kind defines the vertex data kind to use
  20397. * @returns null
  20398. */
  20399. AbstractMesh.prototype.getVerticesData = function (kind) {
  20400. return null;
  20401. };
  20402. /**
  20403. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20404. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20405. * Note that a new underlying VertexBuffer object is created each call.
  20406. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20407. * @param kind defines vertex data kind:
  20408. * * BABYLON.VertexBuffer.PositionKind
  20409. * * BABYLON.VertexBuffer.UVKind
  20410. * * BABYLON.VertexBuffer.UV2Kind
  20411. * * BABYLON.VertexBuffer.UV3Kind
  20412. * * BABYLON.VertexBuffer.UV4Kind
  20413. * * BABYLON.VertexBuffer.UV5Kind
  20414. * * BABYLON.VertexBuffer.UV6Kind
  20415. * * BABYLON.VertexBuffer.ColorKind
  20416. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20417. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20418. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20419. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20420. * @param data defines the data source
  20421. * @param updatable defines if the data must be flagged as updatable (or static)
  20422. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20423. * @returns the current mesh
  20424. */
  20425. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20426. return this;
  20427. };
  20428. /**
  20429. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20430. * If the mesh has no geometry, it is simply returned as it is.
  20431. * @param kind defines vertex data kind:
  20432. * * BABYLON.VertexBuffer.PositionKind
  20433. * * BABYLON.VertexBuffer.UVKind
  20434. * * BABYLON.VertexBuffer.UV2Kind
  20435. * * BABYLON.VertexBuffer.UV3Kind
  20436. * * BABYLON.VertexBuffer.UV4Kind
  20437. * * BABYLON.VertexBuffer.UV5Kind
  20438. * * BABYLON.VertexBuffer.UV6Kind
  20439. * * BABYLON.VertexBuffer.ColorKind
  20440. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20441. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20442. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20443. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20444. * @param data defines the data source
  20445. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20446. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20447. * @returns the current mesh
  20448. */
  20449. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20450. return this;
  20451. };
  20452. /**
  20453. * Sets the mesh indices,
  20454. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20455. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20456. * @param totalVertices Defines the total number of vertices
  20457. * @returns the current mesh
  20458. */
  20459. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20460. return this;
  20461. };
  20462. /**
  20463. * Gets a boolean indicating if specific vertex data is present
  20464. * @param kind defines the vertex data kind to use
  20465. * @returns true is data kind is present
  20466. */
  20467. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20468. return false;
  20469. };
  20470. /**
  20471. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20472. * @returns a BoundingInfo
  20473. */
  20474. AbstractMesh.prototype.getBoundingInfo = function () {
  20475. if (this._masterMesh) {
  20476. return this._masterMesh.getBoundingInfo();
  20477. }
  20478. if (!this._boundingInfo) {
  20479. // this._boundingInfo is being created here
  20480. this._updateBoundingInfo();
  20481. }
  20482. // cannot be null.
  20483. return this._boundingInfo;
  20484. };
  20485. /**
  20486. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20487. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20488. * @returns the current mesh
  20489. */
  20490. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20491. if (includeDescendants === void 0) { includeDescendants = true; }
  20492. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20493. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20494. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20495. if (maxDimension === 0) {
  20496. return this;
  20497. }
  20498. var scale = 1 / maxDimension;
  20499. this.scaling.scaleInPlace(scale);
  20500. return this;
  20501. };
  20502. /**
  20503. * Overwrite the current bounding info
  20504. * @param boundingInfo defines the new bounding info
  20505. * @returns the current mesh
  20506. */
  20507. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20508. this._boundingInfo = boundingInfo;
  20509. return this;
  20510. };
  20511. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20512. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20513. get: function () {
  20514. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20515. },
  20516. enumerable: true,
  20517. configurable: true
  20518. });
  20519. /** @hidden */
  20520. AbstractMesh.prototype._preActivate = function () {
  20521. };
  20522. /** @hidden */
  20523. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20524. };
  20525. /** @hidden */
  20526. AbstractMesh.prototype._activate = function (renderId) {
  20527. this._renderId = renderId;
  20528. };
  20529. /**
  20530. * Gets the current world matrix
  20531. * @returns a Matrix
  20532. */
  20533. AbstractMesh.prototype.getWorldMatrix = function () {
  20534. if (this._masterMesh) {
  20535. return this._masterMesh.getWorldMatrix();
  20536. }
  20537. return _super.prototype.getWorldMatrix.call(this);
  20538. };
  20539. /** @hidden */
  20540. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20541. if (this._masterMesh) {
  20542. return this._masterMesh._getWorldMatrixDeterminant();
  20543. }
  20544. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20545. };
  20546. // ================================== Point of View Movement =================================
  20547. /**
  20548. * Perform relative position change from the point of view of behind the front of the mesh.
  20549. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20550. * Supports definition of mesh facing forward or backward
  20551. * @param amountRight defines the distance on the right axis
  20552. * @param amountUp defines the distance on the up axis
  20553. * @param amountForward defines the distance on the forward axis
  20554. * @returns the current mesh
  20555. */
  20556. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20557. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20558. return this;
  20559. };
  20560. /**
  20561. * Calculate relative position change from the point of view of behind the front of the mesh.
  20562. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20563. * Supports definition of mesh facing forward or backward
  20564. * @param amountRight defines the distance on the right axis
  20565. * @param amountUp defines the distance on the up axis
  20566. * @param amountForward defines the distance on the forward axis
  20567. * @returns the new displacement vector
  20568. */
  20569. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20570. var rotMatrix = new BABYLON.Matrix();
  20571. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20572. rotQuaternion.toRotationMatrix(rotMatrix);
  20573. var translationDelta = BABYLON.Vector3.Zero();
  20574. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20575. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20576. return translationDelta;
  20577. };
  20578. // ================================== Point of View Rotation =================================
  20579. /**
  20580. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20581. * Supports definition of mesh facing forward or backward
  20582. * @param flipBack defines the flip
  20583. * @param twirlClockwise defines the twirl
  20584. * @param tiltRight defines the tilt
  20585. * @returns the current mesh
  20586. */
  20587. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20588. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20589. return this;
  20590. };
  20591. /**
  20592. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20593. * Supports definition of mesh facing forward or backward.
  20594. * @param flipBack defines the flip
  20595. * @param twirlClockwise defines the twirl
  20596. * @param tiltRight defines the tilt
  20597. * @returns the new rotation vector
  20598. */
  20599. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20600. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20601. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20602. };
  20603. /**
  20604. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20605. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20606. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20607. * @returns the new bounding vectors
  20608. */
  20609. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20610. if (includeDescendants === void 0) { includeDescendants = true; }
  20611. if (predicate === void 0) { predicate = null; }
  20612. // Ensures that all world matrix will be recomputed.
  20613. this.getScene().incrementRenderId();
  20614. this.computeWorldMatrix(true);
  20615. var min;
  20616. var max;
  20617. var boundingInfo = this.getBoundingInfo();
  20618. if (!this.subMeshes) {
  20619. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20620. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20621. }
  20622. else {
  20623. min = boundingInfo.boundingBox.minimumWorld;
  20624. max = boundingInfo.boundingBox.maximumWorld;
  20625. }
  20626. if (includeDescendants) {
  20627. var descendants = this.getDescendants(false);
  20628. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20629. var descendant = descendants_1[_i];
  20630. var childMesh = descendant;
  20631. childMesh.computeWorldMatrix(true);
  20632. // Filters meshes based on custom predicate function.
  20633. if (predicate && !predicate(childMesh)) {
  20634. continue;
  20635. }
  20636. //make sure we have the needed params to get mix and max
  20637. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20638. continue;
  20639. }
  20640. var childBoundingInfo = childMesh.getBoundingInfo();
  20641. var boundingBox = childBoundingInfo.boundingBox;
  20642. var minBox = boundingBox.minimumWorld;
  20643. var maxBox = boundingBox.maximumWorld;
  20644. BABYLON.Tools.CheckExtends(minBox, min, max);
  20645. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20646. }
  20647. }
  20648. return {
  20649. min: min,
  20650. max: max
  20651. };
  20652. };
  20653. /** @hidden */
  20654. AbstractMesh.prototype._updateBoundingInfo = function () {
  20655. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20656. this._boundingInfo.update(this.worldMatrixFromCache);
  20657. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20658. return this;
  20659. };
  20660. /** @hidden */
  20661. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20662. if (!this.subMeshes) {
  20663. return this;
  20664. }
  20665. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20666. var subMesh = this.subMeshes[subIndex];
  20667. if (!subMesh.IsGlobal) {
  20668. subMesh.updateBoundingInfo(matrix);
  20669. }
  20670. }
  20671. return this;
  20672. };
  20673. /** @hidden */
  20674. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20675. // Bounding info
  20676. this._updateBoundingInfo();
  20677. };
  20678. /**
  20679. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20680. * A mesh is in the frustum if its bounding box intersects the frustum
  20681. * @param frustumPlanes defines the frustum to test
  20682. * @returns true if the mesh is in the frustum planes
  20683. */
  20684. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20685. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20686. };
  20687. /**
  20688. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20689. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20690. * @param frustumPlanes defines the frustum to test
  20691. * @returns true if the mesh is completely in the frustum planes
  20692. */
  20693. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20694. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20695. };
  20696. /**
  20697. * True if the mesh intersects another mesh or a SolidParticle object
  20698. * @param mesh defines a target mesh or SolidParticle to test
  20699. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20700. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20701. * @returns true if there is an intersection
  20702. */
  20703. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20704. if (precise === void 0) { precise = false; }
  20705. if (!this._boundingInfo || !mesh._boundingInfo) {
  20706. return false;
  20707. }
  20708. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20709. return true;
  20710. }
  20711. if (includeDescendants) {
  20712. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20713. var child = _a[_i];
  20714. if (child.intersectsMesh(mesh, precise, true)) {
  20715. return true;
  20716. }
  20717. }
  20718. }
  20719. return false;
  20720. };
  20721. /**
  20722. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20723. * @param point defines the point to test
  20724. * @returns true if there is an intersection
  20725. */
  20726. AbstractMesh.prototype.intersectsPoint = function (point) {
  20727. if (!this._boundingInfo) {
  20728. return false;
  20729. }
  20730. return this._boundingInfo.intersectsPoint(point);
  20731. };
  20732. /**
  20733. * Gets the current physics impostor
  20734. * @see http://doc.babylonjs.com/features/physics_engine
  20735. * @returns a physics impostor or null
  20736. */
  20737. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20738. return this.physicsImpostor;
  20739. };
  20740. /**
  20741. * Gets the position of the current mesh in camera space
  20742. * @param camera defines the camera to use
  20743. * @returns a position
  20744. */
  20745. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20746. if (camera === void 0) { camera = null; }
  20747. if (!camera) {
  20748. camera = this.getScene().activeCamera;
  20749. }
  20750. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20751. };
  20752. /**
  20753. * Returns the distance from the mesh to the active camera
  20754. * @param camera defines the camera to use
  20755. * @returns the distance
  20756. */
  20757. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20758. if (camera === void 0) { camera = null; }
  20759. if (!camera) {
  20760. camera = this.getScene().activeCamera;
  20761. }
  20762. return this.absolutePosition.subtract(camera.position).length();
  20763. };
  20764. /**
  20765. * Apply a physic impulse to the mesh
  20766. * @param force defines the force to apply
  20767. * @param contactPoint defines where to apply the force
  20768. * @returns the current mesh
  20769. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20770. */
  20771. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20772. if (!this.physicsImpostor) {
  20773. return this;
  20774. }
  20775. this.physicsImpostor.applyImpulse(force, contactPoint);
  20776. return this;
  20777. };
  20778. /**
  20779. * Creates a physic joint between two meshes
  20780. * @param otherMesh defines the other mesh to use
  20781. * @param pivot1 defines the pivot to use on this mesh
  20782. * @param pivot2 defines the pivot to use on the other mesh
  20783. * @param options defines additional options (can be plugin dependent)
  20784. * @returns the current mesh
  20785. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20786. */
  20787. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20788. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20789. return this;
  20790. }
  20791. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20792. mainPivot: pivot1,
  20793. connectedPivot: pivot2,
  20794. nativeParams: options
  20795. });
  20796. return this;
  20797. };
  20798. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20799. // Collisions
  20800. /**
  20801. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20802. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20803. */
  20804. get: function () {
  20805. return this._checkCollisions;
  20806. },
  20807. set: function (collisionEnabled) {
  20808. this._checkCollisions = collisionEnabled;
  20809. if (this.getScene().workerCollisions) {
  20810. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20811. }
  20812. },
  20813. enumerable: true,
  20814. configurable: true
  20815. });
  20816. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20817. /**
  20818. * Gets Collider object used to compute collisions (not physics)
  20819. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20820. */
  20821. get: function () {
  20822. return this._collider;
  20823. },
  20824. enumerable: true,
  20825. configurable: true
  20826. });
  20827. /**
  20828. * Move the mesh using collision engine
  20829. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20830. * @param displacement defines the requested displacement vector
  20831. * @returns the current mesh
  20832. */
  20833. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20834. var globalPosition = this.getAbsolutePosition();
  20835. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20836. if (!this._collider) {
  20837. this._collider = new BABYLON.Collider();
  20838. }
  20839. this._collider._radius = this.ellipsoid;
  20840. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20841. return this;
  20842. };
  20843. // Submeshes octree
  20844. /**
  20845. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20846. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20847. * @param maxCapacity defines the maximum size of each block (64 by default)
  20848. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20849. * @returns the new octree
  20850. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20851. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20852. */
  20853. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20854. if (maxCapacity === void 0) { maxCapacity = 64; }
  20855. if (maxDepth === void 0) { maxDepth = 2; }
  20856. if (!this._submeshesOctree) {
  20857. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20858. }
  20859. this.computeWorldMatrix(true);
  20860. var boundingInfo = this.getBoundingInfo();
  20861. // Update octree
  20862. var bbox = boundingInfo.boundingBox;
  20863. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20864. return this._submeshesOctree;
  20865. };
  20866. // Collisions
  20867. /** @hidden */
  20868. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20869. this._generatePointsArray();
  20870. if (!this._positions) {
  20871. return this;
  20872. }
  20873. // Transformation
  20874. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20875. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20876. subMesh._lastColliderWorldVertices = [];
  20877. subMesh._trianglePlanes = [];
  20878. var start = subMesh.verticesStart;
  20879. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20880. for (var i = start; i < end; i++) {
  20881. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20882. }
  20883. }
  20884. // Collide
  20885. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20886. if (collider.collisionFound) {
  20887. collider.collidedMesh = this;
  20888. }
  20889. return this;
  20890. };
  20891. /** @hidden */
  20892. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20893. var subMeshes;
  20894. var len;
  20895. // Octrees
  20896. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20897. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20898. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20899. len = intersections.length;
  20900. subMeshes = intersections.data;
  20901. }
  20902. else {
  20903. subMeshes = this.subMeshes;
  20904. len = subMeshes.length;
  20905. }
  20906. for (var index = 0; index < len; index++) {
  20907. var subMesh = subMeshes[index];
  20908. // Bounding test
  20909. if (len > 1 && !subMesh._checkCollision(collider))
  20910. continue;
  20911. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20912. }
  20913. return this;
  20914. };
  20915. /** @hidden */
  20916. AbstractMesh.prototype._checkCollision = function (collider) {
  20917. // Bounding box test
  20918. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20919. return this;
  20920. // Transformation matrix
  20921. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20922. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20923. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20924. return this;
  20925. };
  20926. // Picking
  20927. /** @hidden */
  20928. AbstractMesh.prototype._generatePointsArray = function () {
  20929. return false;
  20930. };
  20931. /**
  20932. * Checks if the passed Ray intersects with the mesh
  20933. * @param ray defines the ray to use
  20934. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20935. * @returns the picking info
  20936. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20937. */
  20938. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20939. var pickingInfo = new BABYLON.PickingInfo();
  20940. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20941. return pickingInfo;
  20942. }
  20943. if (!this._generatePointsArray()) {
  20944. return pickingInfo;
  20945. }
  20946. var intersectInfo = null;
  20947. // Octrees
  20948. var subMeshes;
  20949. var len;
  20950. if (this._submeshesOctree && this.useOctreeForPicking) {
  20951. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20952. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20953. len = intersections.length;
  20954. subMeshes = intersections.data;
  20955. }
  20956. else {
  20957. subMeshes = this.subMeshes;
  20958. len = subMeshes.length;
  20959. }
  20960. for (var index = 0; index < len; index++) {
  20961. var subMesh = subMeshes[index];
  20962. // Bounding test
  20963. if (len > 1 && !subMesh.canIntersects(ray))
  20964. continue;
  20965. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20966. if (currentIntersectInfo) {
  20967. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20968. intersectInfo = currentIntersectInfo;
  20969. intersectInfo.subMeshId = index;
  20970. if (fastCheck) {
  20971. break;
  20972. }
  20973. }
  20974. }
  20975. }
  20976. if (intersectInfo) {
  20977. // Get picked point
  20978. var world = this.getWorldMatrix();
  20979. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20980. var direction = ray.direction.clone();
  20981. direction = direction.scale(intersectInfo.distance);
  20982. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20983. var pickedPoint = worldOrigin.add(worldDirection);
  20984. // Return result
  20985. pickingInfo.hit = true;
  20986. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20987. pickingInfo.pickedPoint = pickedPoint;
  20988. pickingInfo.pickedMesh = this;
  20989. pickingInfo.bu = intersectInfo.bu || 0;
  20990. pickingInfo.bv = intersectInfo.bv || 0;
  20991. pickingInfo.faceId = intersectInfo.faceId;
  20992. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20993. return pickingInfo;
  20994. }
  20995. return pickingInfo;
  20996. };
  20997. /**
  20998. * Clones the current mesh
  20999. * @param name defines the mesh name
  21000. * @param newParent defines the new mesh parent
  21001. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21002. * @returns the new mesh
  21003. */
  21004. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21005. return null;
  21006. };
  21007. /**
  21008. * Disposes all the submeshes of the current meshnp
  21009. * @returns the current mesh
  21010. */
  21011. AbstractMesh.prototype.releaseSubMeshes = function () {
  21012. if (this.subMeshes) {
  21013. while (this.subMeshes.length) {
  21014. this.subMeshes[0].dispose();
  21015. }
  21016. }
  21017. else {
  21018. this.subMeshes = new Array();
  21019. }
  21020. return this;
  21021. };
  21022. /**
  21023. * Releases resources associated with this abstract mesh.
  21024. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21025. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21026. */
  21027. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21028. var _this = this;
  21029. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21030. var index;
  21031. // Smart Array Retainers.
  21032. this.getScene().freeActiveMeshes();
  21033. this.getScene().freeRenderingGroups();
  21034. // Action manager
  21035. if (this.actionManager !== undefined && this.actionManager !== null) {
  21036. this.actionManager.dispose();
  21037. this.actionManager = null;
  21038. }
  21039. // Skeleton
  21040. this._skeleton = null;
  21041. // Physics
  21042. if (this.physicsImpostor) {
  21043. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  21044. }
  21045. // Intersections in progress
  21046. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21047. var other = this._intersectionsInProgress[index];
  21048. var pos = other._intersectionsInProgress.indexOf(this);
  21049. other._intersectionsInProgress.splice(pos, 1);
  21050. }
  21051. this._intersectionsInProgress = [];
  21052. // Lights
  21053. var lights = this.getScene().lights;
  21054. lights.forEach(function (light) {
  21055. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21056. if (meshIndex !== -1) {
  21057. light.includedOnlyMeshes.splice(meshIndex, 1);
  21058. }
  21059. meshIndex = light.excludedMeshes.indexOf(_this);
  21060. if (meshIndex !== -1) {
  21061. light.excludedMeshes.splice(meshIndex, 1);
  21062. }
  21063. // Shadow generators
  21064. var generator = light.getShadowGenerator();
  21065. if (generator) {
  21066. var shadowMap = generator.getShadowMap();
  21067. if (shadowMap && shadowMap.renderList) {
  21068. meshIndex = shadowMap.renderList.indexOf(_this);
  21069. if (meshIndex !== -1) {
  21070. shadowMap.renderList.splice(meshIndex, 1);
  21071. }
  21072. }
  21073. }
  21074. });
  21075. // Edges
  21076. if (this._edgesRenderer) {
  21077. this._edgesRenderer.dispose();
  21078. this._edgesRenderer = null;
  21079. }
  21080. // SubMeshes
  21081. if (this.getClassName() !== "InstancedMesh") {
  21082. this.releaseSubMeshes();
  21083. }
  21084. // Octree
  21085. var sceneOctree = this.getScene().selectionOctree;
  21086. if (sceneOctree !== undefined && sceneOctree !== null) {
  21087. var index = sceneOctree.dynamicContent.indexOf(this);
  21088. if (index !== -1) {
  21089. sceneOctree.dynamicContent.splice(index, 1);
  21090. }
  21091. }
  21092. // Query
  21093. var engine = this.getScene().getEngine();
  21094. if (this._occlusionQuery) {
  21095. this._isOcclusionQueryInProgress = false;
  21096. engine.deleteQuery(this._occlusionQuery);
  21097. this._occlusionQuery = null;
  21098. }
  21099. // Engine
  21100. engine.wipeCaches();
  21101. // Remove from scene
  21102. this.getScene().removeMesh(this);
  21103. if (disposeMaterialAndTextures) {
  21104. if (this.material) {
  21105. this.material.dispose(false, true);
  21106. }
  21107. }
  21108. if (!doNotRecurse) {
  21109. // Particles
  21110. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21111. if (this.getScene().particleSystems[index].emitter === this) {
  21112. this.getScene().particleSystems[index].dispose();
  21113. index--;
  21114. }
  21115. }
  21116. }
  21117. // facet data
  21118. if (this._facetDataEnabled) {
  21119. this.disableFacetData();
  21120. }
  21121. this.onAfterWorldMatrixUpdateObservable.clear();
  21122. this.onCollideObservable.clear();
  21123. this.onCollisionPositionChangeObservable.clear();
  21124. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21125. };
  21126. /**
  21127. * Adds the passed mesh as a child to the current mesh
  21128. * @param mesh defines the child mesh
  21129. * @returns the current mesh
  21130. */
  21131. AbstractMesh.prototype.addChild = function (mesh) {
  21132. mesh.setParent(this);
  21133. return this;
  21134. };
  21135. /**
  21136. * Removes the passed mesh from the current mesh children list
  21137. * @param mesh defines the child mesh
  21138. * @returns the current mesh
  21139. */
  21140. AbstractMesh.prototype.removeChild = function (mesh) {
  21141. mesh.setParent(null);
  21142. return this;
  21143. };
  21144. // Facet data
  21145. /** @hidden */
  21146. AbstractMesh.prototype._initFacetData = function () {
  21147. if (!this._facetNormals) {
  21148. this._facetNormals = new Array();
  21149. }
  21150. if (!this._facetPositions) {
  21151. this._facetPositions = new Array();
  21152. }
  21153. if (!this._facetPartitioning) {
  21154. this._facetPartitioning = new Array();
  21155. }
  21156. this._facetNb = (this.getIndices().length / 3) | 0;
  21157. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21158. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21159. for (var f = 0; f < this._facetNb; f++) {
  21160. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21161. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21162. }
  21163. this._facetDataEnabled = true;
  21164. return this;
  21165. };
  21166. /**
  21167. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21168. * This method can be called within the render loop.
  21169. * 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
  21170. * @returns the current mesh
  21171. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21172. */
  21173. AbstractMesh.prototype.updateFacetData = function () {
  21174. if (!this._facetDataEnabled) {
  21175. this._initFacetData();
  21176. }
  21177. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21178. var indices = this.getIndices();
  21179. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21180. var bInfo = this.getBoundingInfo();
  21181. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21182. // init arrays, matrix and sort function on first call
  21183. this._facetDepthSortEnabled = true;
  21184. if (indices instanceof Uint16Array) {
  21185. this._depthSortedIndices = new Uint16Array(indices);
  21186. }
  21187. else if (indices instanceof Uint32Array) {
  21188. this._depthSortedIndices = new Uint32Array(indices);
  21189. }
  21190. else {
  21191. var needs32bits = false;
  21192. for (var i = 0; i < indices.length; i++) {
  21193. if (indices[i] > 65535) {
  21194. needs32bits = true;
  21195. break;
  21196. }
  21197. }
  21198. if (needs32bits) {
  21199. this._depthSortedIndices = new Uint32Array(indices);
  21200. }
  21201. else {
  21202. this._depthSortedIndices = new Uint16Array(indices);
  21203. }
  21204. }
  21205. this._facetDepthSortFunction = function (f1, f2) {
  21206. return (f2.sqDistance - f1.sqDistance);
  21207. };
  21208. if (!this._facetDepthSortFrom) {
  21209. var camera = this.getScene().activeCamera;
  21210. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21211. }
  21212. this._depthSortedFacets = [];
  21213. for (var f = 0; f < this._facetNb; f++) {
  21214. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21215. this._depthSortedFacets.push(depthSortedFacet);
  21216. }
  21217. this._invertedMatrix = BABYLON.Matrix.Identity();
  21218. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21219. }
  21220. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21221. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21222. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21223. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21224. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21225. this._subDiv.max = this._partitioningSubdivisions;
  21226. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21227. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21228. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21229. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21230. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21231. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21232. // set the parameters for ComputeNormals()
  21233. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21234. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21235. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21236. this._facetParameters.bInfo = bInfo;
  21237. this._facetParameters.bbSize = this._bbSize;
  21238. this._facetParameters.subDiv = this._subDiv;
  21239. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21240. this._facetParameters.depthSort = this._facetDepthSort;
  21241. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21242. this.computeWorldMatrix(true);
  21243. this._worldMatrix.invertToRef(this._invertedMatrix);
  21244. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21245. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21246. }
  21247. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21248. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21249. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21250. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21251. var l = (this._depthSortedIndices.length / 3) | 0;
  21252. for (var f = 0; f < l; f++) {
  21253. var sind = this._depthSortedFacets[f].ind;
  21254. this._depthSortedIndices[f * 3] = indices[sind];
  21255. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21256. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21257. }
  21258. this.updateIndices(this._depthSortedIndices);
  21259. }
  21260. return this;
  21261. };
  21262. /**
  21263. * Returns the facetLocalNormals array.
  21264. * The normals are expressed in the mesh local spac
  21265. * @returns an array of Vector3
  21266. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21267. */
  21268. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21269. if (!this._facetNormals) {
  21270. this.updateFacetData();
  21271. }
  21272. return this._facetNormals;
  21273. };
  21274. /**
  21275. * Returns the facetLocalPositions array.
  21276. * The facet positions are expressed in the mesh local space
  21277. * @returns an array of Vector3
  21278. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21279. */
  21280. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21281. if (!this._facetPositions) {
  21282. this.updateFacetData();
  21283. }
  21284. return this._facetPositions;
  21285. };
  21286. /**
  21287. * Returns the facetLocalPartioning array
  21288. * @returns an array of array of numbers
  21289. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21290. */
  21291. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21292. if (!this._facetPartitioning) {
  21293. this.updateFacetData();
  21294. }
  21295. return this._facetPartitioning;
  21296. };
  21297. /**
  21298. * Returns the i-th facet position in the world system.
  21299. * This method allocates a new Vector3 per call
  21300. * @param i defines the facet index
  21301. * @returns a new Vector3
  21302. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21303. */
  21304. AbstractMesh.prototype.getFacetPosition = function (i) {
  21305. var pos = BABYLON.Vector3.Zero();
  21306. this.getFacetPositionToRef(i, pos);
  21307. return pos;
  21308. };
  21309. /**
  21310. * Sets the reference Vector3 with the i-th facet position in the world system
  21311. * @param i defines the facet index
  21312. * @param ref defines the target vector
  21313. * @returns the current mesh
  21314. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21315. */
  21316. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21317. var localPos = (this.getFacetLocalPositions())[i];
  21318. var world = this.getWorldMatrix();
  21319. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21320. return this;
  21321. };
  21322. /**
  21323. * Returns the i-th facet normal in the world system.
  21324. * This method allocates a new Vector3 per call
  21325. * @param i defines the facet index
  21326. * @returns a new Vector3
  21327. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21328. */
  21329. AbstractMesh.prototype.getFacetNormal = function (i) {
  21330. var norm = BABYLON.Vector3.Zero();
  21331. this.getFacetNormalToRef(i, norm);
  21332. return norm;
  21333. };
  21334. /**
  21335. * Sets the reference Vector3 with the i-th facet normal in the world system
  21336. * @param i defines the facet index
  21337. * @param ref defines the target vector
  21338. * @returns the current mesh
  21339. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21340. */
  21341. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21342. var localNorm = (this.getFacetLocalNormals())[i];
  21343. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21344. return this;
  21345. };
  21346. /**
  21347. * 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)
  21348. * @param x defines x coordinate
  21349. * @param y defines y coordinate
  21350. * @param z defines z coordinate
  21351. * @returns the array of facet indexes
  21352. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21353. */
  21354. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21355. var bInfo = this.getBoundingInfo();
  21356. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21357. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21358. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21359. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21360. return null;
  21361. }
  21362. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21363. };
  21364. /**
  21365. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21366. * @param projected sets as the (x,y,z) world projection on the facet
  21367. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21368. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21369. * @param x defines x coordinate
  21370. * @param y defines y coordinate
  21371. * @param z defines z coordinate
  21372. * @returns the face index if found (or null instead)
  21373. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21374. */
  21375. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21376. if (checkFace === void 0) { checkFace = false; }
  21377. if (facing === void 0) { facing = true; }
  21378. var world = this.getWorldMatrix();
  21379. var invMat = BABYLON.Tmp.Matrix[5];
  21380. world.invertToRef(invMat);
  21381. var invVect = BABYLON.Tmp.Vector3[8];
  21382. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21383. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21384. if (projected) {
  21385. // tranform the local computed projected vector to world coordinates
  21386. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21387. }
  21388. return closest;
  21389. };
  21390. /**
  21391. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21392. * @param projected sets as the (x,y,z) local projection on the facet
  21393. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21394. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21395. * @param x defines x coordinate
  21396. * @param y defines y coordinate
  21397. * @param z defines z coordinate
  21398. * @returns the face index if found (or null instead)
  21399. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21400. */
  21401. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21402. if (checkFace === void 0) { checkFace = false; }
  21403. if (facing === void 0) { facing = true; }
  21404. var closest = null;
  21405. var tmpx = 0.0;
  21406. var tmpy = 0.0;
  21407. var tmpz = 0.0;
  21408. var d = 0.0; // tmp dot facet normal * facet position
  21409. var t0 = 0.0;
  21410. var projx = 0.0;
  21411. var projy = 0.0;
  21412. var projz = 0.0;
  21413. // Get all the facets in the same partitioning block than (x, y, z)
  21414. var facetPositions = this.getFacetLocalPositions();
  21415. var facetNormals = this.getFacetLocalNormals();
  21416. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21417. if (!facetsInBlock) {
  21418. return null;
  21419. }
  21420. // Get the closest facet to (x, y, z)
  21421. var shortest = Number.MAX_VALUE; // init distance vars
  21422. var tmpDistance = shortest;
  21423. var fib; // current facet in the block
  21424. var norm; // current facet normal
  21425. var p0; // current facet barycenter position
  21426. // loop on all the facets in the current partitioning block
  21427. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21428. fib = facetsInBlock[idx];
  21429. norm = facetNormals[fib];
  21430. p0 = facetPositions[fib];
  21431. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21432. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21433. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21434. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21435. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21436. projx = x + norm.x * t0;
  21437. projy = y + norm.y * t0;
  21438. projz = z + norm.z * t0;
  21439. tmpx = projx - x;
  21440. tmpy = projy - y;
  21441. tmpz = projz - z;
  21442. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21443. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21444. shortest = tmpDistance;
  21445. closest = fib;
  21446. if (projected) {
  21447. projected.x = projx;
  21448. projected.y = projy;
  21449. projected.z = projz;
  21450. }
  21451. }
  21452. }
  21453. }
  21454. return closest;
  21455. };
  21456. /**
  21457. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21458. * @returns the parameters
  21459. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21460. */
  21461. AbstractMesh.prototype.getFacetDataParameters = function () {
  21462. return this._facetParameters;
  21463. };
  21464. /**
  21465. * Disables the feature FacetData and frees the related memory
  21466. * @returns the current mesh
  21467. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21468. */
  21469. AbstractMesh.prototype.disableFacetData = function () {
  21470. if (this._facetDataEnabled) {
  21471. this._facetDataEnabled = false;
  21472. this._facetPositions = new Array();
  21473. this._facetNormals = new Array();
  21474. this._facetPartitioning = new Array();
  21475. this._facetParameters = null;
  21476. this._depthSortedIndices = new Uint32Array(0);
  21477. }
  21478. return this;
  21479. };
  21480. /**
  21481. * Updates the AbstractMesh indices array
  21482. * @param indices defines the data source
  21483. * @returns the current mesh
  21484. */
  21485. AbstractMesh.prototype.updateIndices = function (indices) {
  21486. return this;
  21487. };
  21488. /**
  21489. * Creates new normals data for the mesh
  21490. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21491. * @returns the current mesh
  21492. */
  21493. AbstractMesh.prototype.createNormals = function (updatable) {
  21494. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21495. var indices = this.getIndices();
  21496. var normals;
  21497. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21498. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21499. }
  21500. else {
  21501. normals = [];
  21502. }
  21503. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21504. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21505. return this;
  21506. };
  21507. /**
  21508. * Align the mesh with a normal
  21509. * @param normal defines the normal to use
  21510. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21511. * @returns the current mesh
  21512. */
  21513. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21514. if (!upDirection) {
  21515. upDirection = BABYLON.Axis.Y;
  21516. }
  21517. var axisX = BABYLON.Tmp.Vector3[0];
  21518. var axisZ = BABYLON.Tmp.Vector3[1];
  21519. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21520. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21521. if (this.rotationQuaternion) {
  21522. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21523. }
  21524. else {
  21525. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21526. }
  21527. return this;
  21528. };
  21529. /** @hidden */
  21530. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21531. var engine = this.getEngine();
  21532. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21533. this._isOccluded = false;
  21534. return;
  21535. }
  21536. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21537. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21538. if (isOcclusionQueryAvailable) {
  21539. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21540. this._isOcclusionQueryInProgress = false;
  21541. this._occlusionInternalRetryCounter = 0;
  21542. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21543. }
  21544. else {
  21545. this._occlusionInternalRetryCounter++;
  21546. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21547. this._isOcclusionQueryInProgress = false;
  21548. this._occlusionInternalRetryCounter = 0;
  21549. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21550. // if strict continue the last state of the object.
  21551. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21552. }
  21553. else {
  21554. return;
  21555. }
  21556. }
  21557. }
  21558. var scene = this.getScene();
  21559. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21560. if (!this._occlusionQuery) {
  21561. this._occlusionQuery = engine.createQuery();
  21562. }
  21563. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21564. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21565. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21566. this._isOcclusionQueryInProgress = true;
  21567. };
  21568. /** No occlusion */
  21569. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21570. /** Occlusion set to optimisitic */
  21571. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21572. /** Occlusion set to strict */
  21573. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21574. /** Use an accurante occlusion algorithm */
  21575. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21576. /** Use a conservative occlusion algorithm */
  21577. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21578. return AbstractMesh;
  21579. }(BABYLON.TransformNode));
  21580. BABYLON.AbstractMesh = AbstractMesh;
  21581. })(BABYLON || (BABYLON = {}));
  21582. //# sourceMappingURL=babylon.abstractMesh.js.map
  21583. var BABYLON;
  21584. (function (BABYLON) {
  21585. /**
  21586. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21587. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21588. * 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.
  21589. */
  21590. var Light = /** @class */ (function (_super) {
  21591. __extends(Light, _super);
  21592. /**
  21593. * Creates a Light object in the scene.
  21594. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21595. * @param name The firendly name of the light
  21596. * @param scene The scene the light belongs too
  21597. */
  21598. function Light(name, scene) {
  21599. var _this = _super.call(this, name, scene) || this;
  21600. /**
  21601. * Diffuse gives the basic color to an object.
  21602. */
  21603. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21604. /**
  21605. * Specular produces a highlight color on an object.
  21606. * Note: This is note affecting PBR materials.
  21607. */
  21608. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21609. /**
  21610. * Strength of the light.
  21611. * Note: By default it is define in the framework own unit.
  21612. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21613. */
  21614. _this.intensity = 1.0;
  21615. /**
  21616. * Defines how far from the source the light is impacting in scene units.
  21617. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21618. */
  21619. _this.range = Number.MAX_VALUE;
  21620. /**
  21621. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21622. * of light.
  21623. */
  21624. _this._photometricScale = 1.0;
  21625. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21626. _this._radius = 0.00001;
  21627. /**
  21628. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21629. * exceeding the number allowed of the materials.
  21630. */
  21631. _this.renderPriority = 0;
  21632. _this._shadowEnabled = true;
  21633. _this._excludeWithLayerMask = 0;
  21634. _this._includeOnlyWithLayerMask = 0;
  21635. _this._lightmapMode = 0;
  21636. /**
  21637. * @hidden Internal use only.
  21638. */
  21639. _this._excludedMeshesIds = new Array();
  21640. /**
  21641. * @hidden Internal use only.
  21642. */
  21643. _this._includedOnlyMeshesIds = new Array();
  21644. _this.getScene().addLight(_this);
  21645. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21646. _this._buildUniformLayout();
  21647. _this.includedOnlyMeshes = new Array();
  21648. _this.excludedMeshes = new Array();
  21649. _this._resyncMeshes();
  21650. return _this;
  21651. }
  21652. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21653. /**
  21654. * If every light affecting the material is in this lightmapMode,
  21655. * material.lightmapTexture adds or multiplies
  21656. * (depends on material.useLightmapAsShadowmap)
  21657. * after every other light calculations.
  21658. */
  21659. get: function () {
  21660. return Light._LIGHTMAP_DEFAULT;
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21666. /**
  21667. * material.lightmapTexture as only diffuse lighting from this light
  21668. * adds only specular lighting from this light
  21669. * adds dynamic shadows
  21670. */
  21671. get: function () {
  21672. return Light._LIGHTMAP_SPECULAR;
  21673. },
  21674. enumerable: true,
  21675. configurable: true
  21676. });
  21677. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21678. /**
  21679. * material.lightmapTexture as only lighting
  21680. * no light calculation from this light
  21681. * only adds dynamic shadows from this light
  21682. */
  21683. get: function () {
  21684. return Light._LIGHTMAP_SHADOWSONLY;
  21685. },
  21686. enumerable: true,
  21687. configurable: true
  21688. });
  21689. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21690. /**
  21691. * Each light type uses the default quantity according to its type:
  21692. * point/spot lights use luminous intensity
  21693. * directional lights use illuminance
  21694. */
  21695. get: function () {
  21696. return Light._INTENSITYMODE_AUTOMATIC;
  21697. },
  21698. enumerable: true,
  21699. configurable: true
  21700. });
  21701. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21702. /**
  21703. * lumen (lm)
  21704. */
  21705. get: function () {
  21706. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21707. },
  21708. enumerable: true,
  21709. configurable: true
  21710. });
  21711. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21712. /**
  21713. * candela (lm/sr)
  21714. */
  21715. get: function () {
  21716. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21717. },
  21718. enumerable: true,
  21719. configurable: true
  21720. });
  21721. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21722. /**
  21723. * lux (lm/m^2)
  21724. */
  21725. get: function () {
  21726. return Light._INTENSITYMODE_ILLUMINANCE;
  21727. },
  21728. enumerable: true,
  21729. configurable: true
  21730. });
  21731. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21732. /**
  21733. * nit (cd/m^2)
  21734. */
  21735. get: function () {
  21736. return Light._INTENSITYMODE_LUMINANCE;
  21737. },
  21738. enumerable: true,
  21739. configurable: true
  21740. });
  21741. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21742. /**
  21743. * Light type const id of the point light.
  21744. */
  21745. get: function () {
  21746. return Light._LIGHTTYPEID_POINTLIGHT;
  21747. },
  21748. enumerable: true,
  21749. configurable: true
  21750. });
  21751. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21752. /**
  21753. * Light type const id of the directional light.
  21754. */
  21755. get: function () {
  21756. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21757. },
  21758. enumerable: true,
  21759. configurable: true
  21760. });
  21761. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21762. /**
  21763. * Light type const id of the spot light.
  21764. */
  21765. get: function () {
  21766. return Light._LIGHTTYPEID_SPOTLIGHT;
  21767. },
  21768. enumerable: true,
  21769. configurable: true
  21770. });
  21771. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21772. /**
  21773. * Light type const id of the hemispheric light.
  21774. */
  21775. get: function () {
  21776. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21777. },
  21778. enumerable: true,
  21779. configurable: true
  21780. });
  21781. Object.defineProperty(Light.prototype, "intensityMode", {
  21782. /**
  21783. * Gets the photometric scale used to interpret the intensity.
  21784. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21785. */
  21786. get: function () {
  21787. return this._intensityMode;
  21788. },
  21789. /**
  21790. * Sets the photometric scale used to interpret the intensity.
  21791. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21792. */
  21793. set: function (value) {
  21794. this._intensityMode = value;
  21795. this._computePhotometricScale();
  21796. },
  21797. enumerable: true,
  21798. configurable: true
  21799. });
  21800. ;
  21801. ;
  21802. Object.defineProperty(Light.prototype, "radius", {
  21803. /**
  21804. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21805. */
  21806. get: function () {
  21807. return this._radius;
  21808. },
  21809. /**
  21810. * sets the light radius used by PBR Materials to simulate soft area lights.
  21811. */
  21812. set: function (value) {
  21813. this._radius = value;
  21814. this._computePhotometricScale();
  21815. },
  21816. enumerable: true,
  21817. configurable: true
  21818. });
  21819. ;
  21820. ;
  21821. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21822. /**
  21823. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21824. * the current shadow generator.
  21825. */
  21826. get: function () {
  21827. return this._shadowEnabled;
  21828. },
  21829. /**
  21830. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21831. * the current shadow generator.
  21832. */
  21833. set: function (value) {
  21834. if (this._shadowEnabled === value) {
  21835. return;
  21836. }
  21837. this._shadowEnabled = value;
  21838. this._markMeshesAsLightDirty();
  21839. },
  21840. enumerable: true,
  21841. configurable: true
  21842. });
  21843. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21844. /**
  21845. * Gets the only meshes impacted by this light.
  21846. */
  21847. get: function () {
  21848. return this._includedOnlyMeshes;
  21849. },
  21850. /**
  21851. * Sets the only meshes impacted by this light.
  21852. */
  21853. set: function (value) {
  21854. this._includedOnlyMeshes = value;
  21855. this._hookArrayForIncludedOnly(value);
  21856. },
  21857. enumerable: true,
  21858. configurable: true
  21859. });
  21860. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21861. /**
  21862. * Gets the meshes not impacted by this light.
  21863. */
  21864. get: function () {
  21865. return this._excludedMeshes;
  21866. },
  21867. /**
  21868. * Sets the meshes not impacted by this light.
  21869. */
  21870. set: function (value) {
  21871. this._excludedMeshes = value;
  21872. this._hookArrayForExcluded(value);
  21873. },
  21874. enumerable: true,
  21875. configurable: true
  21876. });
  21877. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21878. /**
  21879. * Gets the layer id use to find what meshes are not impacted by the light.
  21880. * Inactive if 0
  21881. */
  21882. get: function () {
  21883. return this._excludeWithLayerMask;
  21884. },
  21885. /**
  21886. * Sets the layer id use to find what meshes are not impacted by the light.
  21887. * Inactive if 0
  21888. */
  21889. set: function (value) {
  21890. this._excludeWithLayerMask = value;
  21891. this._resyncMeshes();
  21892. },
  21893. enumerable: true,
  21894. configurable: true
  21895. });
  21896. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21897. /**
  21898. * Gets the layer id use to find what meshes are impacted by the light.
  21899. * Inactive if 0
  21900. */
  21901. get: function () {
  21902. return this._includeOnlyWithLayerMask;
  21903. },
  21904. /**
  21905. * Sets the layer id use to find what meshes are impacted by the light.
  21906. * Inactive if 0
  21907. */
  21908. set: function (value) {
  21909. this._includeOnlyWithLayerMask = value;
  21910. this._resyncMeshes();
  21911. },
  21912. enumerable: true,
  21913. configurable: true
  21914. });
  21915. Object.defineProperty(Light.prototype, "lightmapMode", {
  21916. /**
  21917. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21918. */
  21919. get: function () {
  21920. return this._lightmapMode;
  21921. },
  21922. /**
  21923. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21924. */
  21925. set: function (value) {
  21926. if (this._lightmapMode === value) {
  21927. return;
  21928. }
  21929. this._lightmapMode = value;
  21930. this._markMeshesAsLightDirty();
  21931. },
  21932. enumerable: true,
  21933. configurable: true
  21934. });
  21935. /**
  21936. * Returns the string "Light".
  21937. * @returns the class name
  21938. */
  21939. Light.prototype.getClassName = function () {
  21940. return "Light";
  21941. };
  21942. /**
  21943. * Converts the light information to a readable string for debug purpose.
  21944. * @param fullDetails Supports for multiple levels of logging within scene loading
  21945. * @returns the human readable light info
  21946. */
  21947. Light.prototype.toString = function (fullDetails) {
  21948. var ret = "Name: " + this.name;
  21949. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21950. if (this.animations) {
  21951. for (var i = 0; i < this.animations.length; i++) {
  21952. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21953. }
  21954. }
  21955. if (fullDetails) {
  21956. }
  21957. return ret;
  21958. };
  21959. /**
  21960. * Set the enabled state of this node.
  21961. * @param value - the new enabled state
  21962. */
  21963. Light.prototype.setEnabled = function (value) {
  21964. _super.prototype.setEnabled.call(this, value);
  21965. this._resyncMeshes();
  21966. };
  21967. /**
  21968. * Returns the Light associated shadow generator if any.
  21969. * @return the associated shadow generator.
  21970. */
  21971. Light.prototype.getShadowGenerator = function () {
  21972. return this._shadowGenerator;
  21973. };
  21974. /**
  21975. * Returns a Vector3, the absolute light position in the World.
  21976. * @returns the world space position of the light
  21977. */
  21978. Light.prototype.getAbsolutePosition = function () {
  21979. return BABYLON.Vector3.Zero();
  21980. };
  21981. /**
  21982. * Specifies if the light will affect the passed mesh.
  21983. * @param mesh The mesh to test against the light
  21984. * @return true the mesh is affected otherwise, false.
  21985. */
  21986. Light.prototype.canAffectMesh = function (mesh) {
  21987. if (!mesh) {
  21988. return true;
  21989. }
  21990. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21991. return false;
  21992. }
  21993. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21994. return false;
  21995. }
  21996. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21997. return false;
  21998. }
  21999. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22000. return false;
  22001. }
  22002. return true;
  22003. };
  22004. /**
  22005. * Computes and Returns the light World matrix.
  22006. * @returns the world matrix
  22007. */
  22008. Light.prototype.getWorldMatrix = function () {
  22009. this._currentRenderId = this.getScene().getRenderId();
  22010. this._childRenderId = this._currentRenderId;
  22011. var worldMatrix = this._getWorldMatrix();
  22012. if (this.parent && this.parent.getWorldMatrix) {
  22013. if (!this._parentedWorldMatrix) {
  22014. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  22015. }
  22016. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  22017. this._markSyncedWithParent();
  22018. return this._parentedWorldMatrix;
  22019. }
  22020. return worldMatrix;
  22021. };
  22022. /**
  22023. * Sort function to order lights for rendering.
  22024. * @param a First Light object to compare to second.
  22025. * @param b Second Light object to compare first.
  22026. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22027. */
  22028. Light.CompareLightsPriority = function (a, b) {
  22029. //shadow-casting lights have priority over non-shadow-casting lights
  22030. //the renderPrioirty is a secondary sort criterion
  22031. if (a.shadowEnabled !== b.shadowEnabled) {
  22032. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22033. }
  22034. return b.renderPriority - a.renderPriority;
  22035. };
  22036. /**
  22037. * Releases resources associated with this node.
  22038. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22039. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22040. */
  22041. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22042. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22043. if (this._shadowGenerator) {
  22044. this._shadowGenerator.dispose();
  22045. this._shadowGenerator = null;
  22046. }
  22047. // Animations
  22048. this.getScene().stopAnimation(this);
  22049. // Remove from meshes
  22050. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22051. var mesh = _a[_i];
  22052. mesh._removeLightSource(this);
  22053. }
  22054. this._uniformBuffer.dispose();
  22055. // Remove from scene
  22056. this.getScene().removeLight(this);
  22057. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22058. };
  22059. /**
  22060. * Returns the light type ID (integer).
  22061. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22062. */
  22063. Light.prototype.getTypeID = function () {
  22064. return 0;
  22065. };
  22066. /**
  22067. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22068. * @returns the scaled intensity in intensity mode unit
  22069. */
  22070. Light.prototype.getScaledIntensity = function () {
  22071. return this._photometricScale * this.intensity;
  22072. };
  22073. /**
  22074. * Returns a new Light object, named "name", from the current one.
  22075. * @param name The name of the cloned light
  22076. * @returns the new created light
  22077. */
  22078. Light.prototype.clone = function (name) {
  22079. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22080. if (!constructor) {
  22081. return null;
  22082. }
  22083. return BABYLON.SerializationHelper.Clone(constructor, this);
  22084. };
  22085. /**
  22086. * Serializes the current light into a Serialization object.
  22087. * @returns the serialized object.
  22088. */
  22089. Light.prototype.serialize = function () {
  22090. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22091. // Type
  22092. serializationObject.type = this.getTypeID();
  22093. // Parent
  22094. if (this.parent) {
  22095. serializationObject.parentId = this.parent.id;
  22096. }
  22097. // Inclusion / exclusions
  22098. if (this.excludedMeshes.length > 0) {
  22099. serializationObject.excludedMeshesIds = [];
  22100. this.excludedMeshes.forEach(function (mesh) {
  22101. serializationObject.excludedMeshesIds.push(mesh.id);
  22102. });
  22103. }
  22104. if (this.includedOnlyMeshes.length > 0) {
  22105. serializationObject.includedOnlyMeshesIds = [];
  22106. this.includedOnlyMeshes.forEach(function (mesh) {
  22107. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22108. });
  22109. }
  22110. // Animations
  22111. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22112. serializationObject.ranges = this.serializeAnimationRanges();
  22113. return serializationObject;
  22114. };
  22115. /**
  22116. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22117. * This new light is named "name" and added to the passed scene.
  22118. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22119. * @param name The friendly name of the light
  22120. * @param scene The scene the new light will belong to
  22121. * @returns the constructor function
  22122. */
  22123. Light.GetConstructorFromName = function (type, name, scene) {
  22124. switch (type) {
  22125. case 0:
  22126. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22127. case 1:
  22128. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22129. case 2:
  22130. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22131. case 3:
  22132. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22133. }
  22134. return null;
  22135. };
  22136. /**
  22137. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22138. * @param parsedLight The JSON representation of the light
  22139. * @param scene The scene to create the parsed light in
  22140. * @returns the created light after parsing
  22141. */
  22142. Light.Parse = function (parsedLight, scene) {
  22143. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22144. if (!constructor) {
  22145. return null;
  22146. }
  22147. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22148. // Inclusion / exclusions
  22149. if (parsedLight.excludedMeshesIds) {
  22150. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22151. }
  22152. if (parsedLight.includedOnlyMeshesIds) {
  22153. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22154. }
  22155. // Parent
  22156. if (parsedLight.parentId) {
  22157. light._waitingParentId = parsedLight.parentId;
  22158. }
  22159. // Animations
  22160. if (parsedLight.animations) {
  22161. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22162. var parsedAnimation = parsedLight.animations[animationIndex];
  22163. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22164. }
  22165. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22166. }
  22167. if (parsedLight.autoAnimate) {
  22168. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22169. }
  22170. return light;
  22171. };
  22172. Light.prototype._hookArrayForExcluded = function (array) {
  22173. var _this = this;
  22174. var oldPush = array.push;
  22175. array.push = function () {
  22176. var items = [];
  22177. for (var _i = 0; _i < arguments.length; _i++) {
  22178. items[_i] = arguments[_i];
  22179. }
  22180. var result = oldPush.apply(array, items);
  22181. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22182. var item = items_1[_a];
  22183. item._resyncLighSource(_this);
  22184. }
  22185. return result;
  22186. };
  22187. var oldSplice = array.splice;
  22188. array.splice = function (index, deleteCount) {
  22189. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22190. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22191. var item = deleted_1[_i];
  22192. item._resyncLighSource(_this);
  22193. }
  22194. return deleted;
  22195. };
  22196. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22197. var item = array_1[_i];
  22198. item._resyncLighSource(this);
  22199. }
  22200. };
  22201. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22202. var _this = this;
  22203. var oldPush = array.push;
  22204. array.push = function () {
  22205. var items = [];
  22206. for (var _i = 0; _i < arguments.length; _i++) {
  22207. items[_i] = arguments[_i];
  22208. }
  22209. var result = oldPush.apply(array, items);
  22210. _this._resyncMeshes();
  22211. return result;
  22212. };
  22213. var oldSplice = array.splice;
  22214. array.splice = function (index, deleteCount) {
  22215. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22216. _this._resyncMeshes();
  22217. return deleted;
  22218. };
  22219. this._resyncMeshes();
  22220. };
  22221. Light.prototype._resyncMeshes = function () {
  22222. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22223. var mesh = _a[_i];
  22224. mesh._resyncLighSource(this);
  22225. }
  22226. };
  22227. /**
  22228. * Forces the meshes to update their light related information in their rendering used effects
  22229. * @hidden Internal Use Only
  22230. */
  22231. Light.prototype._markMeshesAsLightDirty = function () {
  22232. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22233. var mesh = _a[_i];
  22234. if (mesh._lightSources.indexOf(this) !== -1) {
  22235. mesh._markSubMeshesAsLightDirty();
  22236. }
  22237. }
  22238. };
  22239. /**
  22240. * Recomputes the cached photometric scale if needed.
  22241. */
  22242. Light.prototype._computePhotometricScale = function () {
  22243. this._photometricScale = this._getPhotometricScale();
  22244. this.getScene().resetCachedMaterial();
  22245. };
  22246. /**
  22247. * Returns the Photometric Scale according to the light type and intensity mode.
  22248. */
  22249. Light.prototype._getPhotometricScale = function () {
  22250. var photometricScale = 0.0;
  22251. var lightTypeID = this.getTypeID();
  22252. //get photometric mode
  22253. var photometricMode = this.intensityMode;
  22254. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22255. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22256. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22257. }
  22258. else {
  22259. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22260. }
  22261. }
  22262. //compute photometric scale
  22263. switch (lightTypeID) {
  22264. case Light.LIGHTTYPEID_POINTLIGHT:
  22265. case Light.LIGHTTYPEID_SPOTLIGHT:
  22266. switch (photometricMode) {
  22267. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22268. photometricScale = 1.0 / (4.0 * Math.PI);
  22269. break;
  22270. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22271. photometricScale = 1.0;
  22272. break;
  22273. case Light.INTENSITYMODE_LUMINANCE:
  22274. photometricScale = this.radius * this.radius;
  22275. break;
  22276. }
  22277. break;
  22278. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22279. switch (photometricMode) {
  22280. case Light.INTENSITYMODE_ILLUMINANCE:
  22281. photometricScale = 1.0;
  22282. break;
  22283. case Light.INTENSITYMODE_LUMINANCE:
  22284. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22285. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22286. var apexAngleRadians = this.radius;
  22287. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22288. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22289. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22290. photometricScale = solidAngle;
  22291. break;
  22292. }
  22293. break;
  22294. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22295. // No fall off in hemisperic light.
  22296. photometricScale = 1.0;
  22297. break;
  22298. }
  22299. return photometricScale;
  22300. };
  22301. /**
  22302. * Reorder the light in the scene according to their defined priority.
  22303. * @hidden Internal Use Only
  22304. */
  22305. Light.prototype._reorderLightsInScene = function () {
  22306. var scene = this.getScene();
  22307. if (this._renderPriority != 0) {
  22308. scene.requireLightSorting = true;
  22309. }
  22310. this.getScene().sortLightsByPriority();
  22311. };
  22312. //lightmapMode Consts
  22313. Light._LIGHTMAP_DEFAULT = 0;
  22314. Light._LIGHTMAP_SPECULAR = 1;
  22315. Light._LIGHTMAP_SHADOWSONLY = 2;
  22316. // Intensity Mode Consts
  22317. Light._INTENSITYMODE_AUTOMATIC = 0;
  22318. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22319. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22320. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22321. Light._INTENSITYMODE_LUMINANCE = 4;
  22322. // Light types ids const.
  22323. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22324. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22325. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22326. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22327. __decorate([
  22328. BABYLON.serializeAsColor3()
  22329. ], Light.prototype, "diffuse", void 0);
  22330. __decorate([
  22331. BABYLON.serializeAsColor3()
  22332. ], Light.prototype, "specular", void 0);
  22333. __decorate([
  22334. BABYLON.serialize()
  22335. ], Light.prototype, "intensity", void 0);
  22336. __decorate([
  22337. BABYLON.serialize()
  22338. ], Light.prototype, "range", void 0);
  22339. __decorate([
  22340. BABYLON.serialize()
  22341. ], Light.prototype, "intensityMode", null);
  22342. __decorate([
  22343. BABYLON.serialize()
  22344. ], Light.prototype, "radius", null);
  22345. __decorate([
  22346. BABYLON.serialize()
  22347. ], Light.prototype, "_renderPriority", void 0);
  22348. __decorate([
  22349. BABYLON.expandToProperty("_reorderLightsInScene")
  22350. ], Light.prototype, "renderPriority", void 0);
  22351. __decorate([
  22352. BABYLON.serialize("shadowEnabled")
  22353. ], Light.prototype, "_shadowEnabled", void 0);
  22354. __decorate([
  22355. BABYLON.serialize("excludeWithLayerMask")
  22356. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22357. __decorate([
  22358. BABYLON.serialize("includeOnlyWithLayerMask")
  22359. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22360. __decorate([
  22361. BABYLON.serialize("lightmapMode")
  22362. ], Light.prototype, "_lightmapMode", void 0);
  22363. return Light;
  22364. }(BABYLON.Node));
  22365. BABYLON.Light = Light;
  22366. })(BABYLON || (BABYLON = {}));
  22367. //# sourceMappingURL=babylon.light.js.map
  22368. var BABYLON;
  22369. (function (BABYLON) {
  22370. var Camera = /** @class */ (function (_super) {
  22371. __extends(Camera, _super);
  22372. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22373. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22374. var _this = _super.call(this, name, scene) || this;
  22375. /**
  22376. * The vector the camera should consider as up.
  22377. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22378. */
  22379. _this.upVector = BABYLON.Vector3.Up();
  22380. _this.orthoLeft = null;
  22381. _this.orthoRight = null;
  22382. _this.orthoBottom = null;
  22383. _this.orthoTop = null;
  22384. /**
  22385. * FOV is set in Radians. (default is 0.8)
  22386. */
  22387. _this.fov = 0.8;
  22388. _this.minZ = 1;
  22389. _this.maxZ = 10000.0;
  22390. _this.inertia = 0.9;
  22391. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22392. _this.isIntermediate = false;
  22393. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22394. /**
  22395. * Restricts the camera to viewing objects with the same layerMask.
  22396. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22397. */
  22398. _this.layerMask = 0x0FFFFFFF;
  22399. /**
  22400. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22401. */
  22402. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22403. // Camera rig members
  22404. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22405. _this._rigCameras = new Array();
  22406. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22407. _this._skipRendering = false;
  22408. _this.customRenderTargets = new Array();
  22409. // Observables
  22410. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22411. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22412. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22413. _this.onRestoreStateObservable = new BABYLON.Observable();
  22414. // Cache
  22415. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22416. _this._projectionMatrix = new BABYLON.Matrix();
  22417. _this._doNotComputeProjectionMatrix = false;
  22418. _this._worldMatrix = BABYLON.Matrix.Identity();
  22419. _this._postProcesses = new Array();
  22420. _this._transformMatrix = BABYLON.Matrix.Zero();
  22421. _this._activeMeshes = new BABYLON.SmartArray(256);
  22422. _this._globalPosition = BABYLON.Vector3.Zero();
  22423. _this._refreshFrustumPlanes = true;
  22424. _this.getScene().addCamera(_this);
  22425. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22426. _this.getScene().activeCamera = _this;
  22427. }
  22428. _this.position = position;
  22429. return _this;
  22430. }
  22431. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22432. get: function () {
  22433. return Camera._PERSPECTIVE_CAMERA;
  22434. },
  22435. enumerable: true,
  22436. configurable: true
  22437. });
  22438. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22439. get: function () {
  22440. return Camera._ORTHOGRAPHIC_CAMERA;
  22441. },
  22442. enumerable: true,
  22443. configurable: true
  22444. });
  22445. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22446. /**
  22447. * This is the default FOV mode for perspective cameras.
  22448. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22449. *
  22450. */
  22451. get: function () {
  22452. return Camera._FOVMODE_VERTICAL_FIXED;
  22453. },
  22454. enumerable: true,
  22455. configurable: true
  22456. });
  22457. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22458. /**
  22459. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22460. *
  22461. */
  22462. get: function () {
  22463. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22464. },
  22465. enumerable: true,
  22466. configurable: true
  22467. });
  22468. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22469. get: function () {
  22470. return Camera._RIG_MODE_NONE;
  22471. },
  22472. enumerable: true,
  22473. configurable: true
  22474. });
  22475. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22476. get: function () {
  22477. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22478. },
  22479. enumerable: true,
  22480. configurable: true
  22481. });
  22482. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22483. get: function () {
  22484. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22485. },
  22486. enumerable: true,
  22487. configurable: true
  22488. });
  22489. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22490. get: function () {
  22491. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22492. },
  22493. enumerable: true,
  22494. configurable: true
  22495. });
  22496. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22497. get: function () {
  22498. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22499. },
  22500. enumerable: true,
  22501. configurable: true
  22502. });
  22503. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22504. get: function () {
  22505. return Camera._RIG_MODE_VR;
  22506. },
  22507. enumerable: true,
  22508. configurable: true
  22509. });
  22510. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22511. get: function () {
  22512. return Camera._RIG_MODE_WEBVR;
  22513. },
  22514. enumerable: true,
  22515. configurable: true
  22516. });
  22517. /**
  22518. * Store current camera state (fov, position, etc..)
  22519. */
  22520. Camera.prototype.storeState = function () {
  22521. this._stateStored = true;
  22522. this._storedFov = this.fov;
  22523. return this;
  22524. };
  22525. /**
  22526. * Restores the camera state values if it has been stored. You must call storeState() first
  22527. */
  22528. Camera.prototype._restoreStateValues = function () {
  22529. if (!this._stateStored) {
  22530. return false;
  22531. }
  22532. this.fov = this._storedFov;
  22533. return true;
  22534. };
  22535. /**
  22536. * Restored camera state. You must call storeState() first
  22537. */
  22538. Camera.prototype.restoreState = function () {
  22539. if (this._restoreStateValues()) {
  22540. this.onRestoreStateObservable.notifyObservers(this);
  22541. return true;
  22542. }
  22543. return false;
  22544. };
  22545. Camera.prototype.getClassName = function () {
  22546. return "Camera";
  22547. };
  22548. /**
  22549. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22550. */
  22551. Camera.prototype.toString = function (fullDetails) {
  22552. var ret = "Name: " + this.name;
  22553. ret += ", type: " + this.getClassName();
  22554. if (this.animations) {
  22555. for (var i = 0; i < this.animations.length; i++) {
  22556. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22557. }
  22558. }
  22559. if (fullDetails) {
  22560. }
  22561. return ret;
  22562. };
  22563. Object.defineProperty(Camera.prototype, "globalPosition", {
  22564. get: function () {
  22565. return this._globalPosition;
  22566. },
  22567. enumerable: true,
  22568. configurable: true
  22569. });
  22570. Camera.prototype.getActiveMeshes = function () {
  22571. return this._activeMeshes;
  22572. };
  22573. Camera.prototype.isActiveMesh = function (mesh) {
  22574. return (this._activeMeshes.indexOf(mesh) !== -1);
  22575. };
  22576. /**
  22577. * Is this camera ready to be used/rendered
  22578. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22579. * @return true if the camera is ready
  22580. */
  22581. Camera.prototype.isReady = function (completeCheck) {
  22582. if (completeCheck === void 0) { completeCheck = false; }
  22583. if (completeCheck) {
  22584. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22585. var pp = _a[_i];
  22586. if (pp && !pp.isReady()) {
  22587. return false;
  22588. }
  22589. }
  22590. }
  22591. return _super.prototype.isReady.call(this, completeCheck);
  22592. };
  22593. //Cache
  22594. Camera.prototype._initCache = function () {
  22595. _super.prototype._initCache.call(this);
  22596. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22597. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22598. this._cache.mode = undefined;
  22599. this._cache.minZ = undefined;
  22600. this._cache.maxZ = undefined;
  22601. this._cache.fov = undefined;
  22602. this._cache.fovMode = undefined;
  22603. this._cache.aspectRatio = undefined;
  22604. this._cache.orthoLeft = undefined;
  22605. this._cache.orthoRight = undefined;
  22606. this._cache.orthoBottom = undefined;
  22607. this._cache.orthoTop = undefined;
  22608. this._cache.renderWidth = undefined;
  22609. this._cache.renderHeight = undefined;
  22610. };
  22611. Camera.prototype._updateCache = function (ignoreParentClass) {
  22612. if (!ignoreParentClass) {
  22613. _super.prototype._updateCache.call(this);
  22614. }
  22615. this._cache.position.copyFrom(this.position);
  22616. this._cache.upVector.copyFrom(this.upVector);
  22617. };
  22618. // Synchronized
  22619. Camera.prototype._isSynchronized = function () {
  22620. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22621. };
  22622. Camera.prototype._isSynchronizedViewMatrix = function () {
  22623. if (!_super.prototype._isSynchronized.call(this))
  22624. return false;
  22625. return this._cache.position.equals(this.position)
  22626. && this._cache.upVector.equals(this.upVector)
  22627. && this.isSynchronizedWithParent();
  22628. };
  22629. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22630. var check = this._cache.mode === this.mode
  22631. && this._cache.minZ === this.minZ
  22632. && this._cache.maxZ === this.maxZ;
  22633. if (!check) {
  22634. return false;
  22635. }
  22636. var engine = this.getEngine();
  22637. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22638. check = this._cache.fov === this.fov
  22639. && this._cache.fovMode === this.fovMode
  22640. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22641. }
  22642. else {
  22643. check = this._cache.orthoLeft === this.orthoLeft
  22644. && this._cache.orthoRight === this.orthoRight
  22645. && this._cache.orthoBottom === this.orthoBottom
  22646. && this._cache.orthoTop === this.orthoTop
  22647. && this._cache.renderWidth === engine.getRenderWidth()
  22648. && this._cache.renderHeight === engine.getRenderHeight();
  22649. }
  22650. return check;
  22651. };
  22652. // Controls
  22653. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22654. };
  22655. Camera.prototype.detachControl = function (element) {
  22656. };
  22657. Camera.prototype.update = function () {
  22658. this._checkInputs();
  22659. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22660. this._updateRigCameras();
  22661. }
  22662. };
  22663. Camera.prototype._checkInputs = function () {
  22664. this.onAfterCheckInputsObservable.notifyObservers(this);
  22665. };
  22666. Object.defineProperty(Camera.prototype, "rigCameras", {
  22667. get: function () {
  22668. return this._rigCameras;
  22669. },
  22670. enumerable: true,
  22671. configurable: true
  22672. });
  22673. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22674. get: function () {
  22675. return this._rigPostProcess;
  22676. },
  22677. enumerable: true,
  22678. configurable: true
  22679. });
  22680. /**
  22681. * Internal, gets the first post proces.
  22682. * @returns the first post process to be run on this camera.
  22683. */
  22684. Camera.prototype._getFirstPostProcess = function () {
  22685. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22686. if (this._postProcesses[ppIndex] !== null) {
  22687. return this._postProcesses[ppIndex];
  22688. }
  22689. }
  22690. return null;
  22691. };
  22692. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22693. // invalidate framebuffer
  22694. var firstPostProcess = this._getFirstPostProcess();
  22695. if (firstPostProcess) {
  22696. firstPostProcess.markTextureDirty();
  22697. }
  22698. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22699. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22700. var cam = this._rigCameras[i];
  22701. var rigPostProcess = cam._rigPostProcess;
  22702. // for VR rig, there does not have to be a post process
  22703. if (rigPostProcess) {
  22704. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22705. if (isPass) {
  22706. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22707. cam.isIntermediate = this._postProcesses.length === 0;
  22708. }
  22709. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22710. rigPostProcess.markTextureDirty();
  22711. }
  22712. else {
  22713. cam._postProcesses = this._postProcesses.slice(0);
  22714. }
  22715. }
  22716. };
  22717. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22718. if (insertAt === void 0) { insertAt = null; }
  22719. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22720. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22721. return 0;
  22722. }
  22723. if (insertAt == null || insertAt < 0) {
  22724. this._postProcesses.push(postProcess);
  22725. }
  22726. else if (this._postProcesses[insertAt] === null) {
  22727. this._postProcesses[insertAt] = postProcess;
  22728. }
  22729. else {
  22730. this._postProcesses.splice(insertAt, 0, postProcess);
  22731. }
  22732. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22733. return this._postProcesses.indexOf(postProcess);
  22734. };
  22735. Camera.prototype.detachPostProcess = function (postProcess) {
  22736. var idx = this._postProcesses.indexOf(postProcess);
  22737. if (idx !== -1) {
  22738. this._postProcesses[idx] = null;
  22739. }
  22740. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22741. };
  22742. Camera.prototype.getWorldMatrix = function () {
  22743. if (this._isSynchronizedViewMatrix()) {
  22744. return this._worldMatrix;
  22745. }
  22746. // Getting the the view matrix will also compute the world matrix.
  22747. this.getViewMatrix();
  22748. return this._worldMatrix;
  22749. };
  22750. Camera.prototype._getViewMatrix = function () {
  22751. return BABYLON.Matrix.Identity();
  22752. };
  22753. Camera.prototype.getViewMatrix = function (force) {
  22754. if (!force && this._isSynchronizedViewMatrix()) {
  22755. return this._computedViewMatrix;
  22756. }
  22757. this.updateCache();
  22758. this._computedViewMatrix = this._getViewMatrix();
  22759. this._currentRenderId = this.getScene().getRenderId();
  22760. this._childRenderId = this._currentRenderId;
  22761. this._refreshFrustumPlanes = true;
  22762. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22763. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22764. }
  22765. this.onViewMatrixChangedObservable.notifyObservers(this);
  22766. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22767. return this._computedViewMatrix;
  22768. };
  22769. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22770. this._doNotComputeProjectionMatrix = true;
  22771. if (projection !== undefined) {
  22772. this._projectionMatrix = projection;
  22773. }
  22774. };
  22775. ;
  22776. Camera.prototype.unfreezeProjectionMatrix = function () {
  22777. this._doNotComputeProjectionMatrix = false;
  22778. };
  22779. ;
  22780. Camera.prototype.getProjectionMatrix = function (force) {
  22781. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22782. return this._projectionMatrix;
  22783. }
  22784. // Cache
  22785. this._cache.mode = this.mode;
  22786. this._cache.minZ = this.minZ;
  22787. this._cache.maxZ = this.maxZ;
  22788. // Matrix
  22789. this._refreshFrustumPlanes = true;
  22790. var engine = this.getEngine();
  22791. var scene = this.getScene();
  22792. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22793. this._cache.fov = this.fov;
  22794. this._cache.fovMode = this.fovMode;
  22795. this._cache.aspectRatio = engine.getAspectRatio(this);
  22796. if (this.minZ <= 0) {
  22797. this.minZ = 0.1;
  22798. }
  22799. if (scene.useRightHandedSystem) {
  22800. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22801. }
  22802. else {
  22803. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22804. }
  22805. }
  22806. else {
  22807. var halfWidth = engine.getRenderWidth() / 2.0;
  22808. var halfHeight = engine.getRenderHeight() / 2.0;
  22809. if (scene.useRightHandedSystem) {
  22810. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22811. }
  22812. else {
  22813. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22814. }
  22815. this._cache.orthoLeft = this.orthoLeft;
  22816. this._cache.orthoRight = this.orthoRight;
  22817. this._cache.orthoBottom = this.orthoBottom;
  22818. this._cache.orthoTop = this.orthoTop;
  22819. this._cache.renderWidth = engine.getRenderWidth();
  22820. this._cache.renderHeight = engine.getRenderHeight();
  22821. }
  22822. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22823. return this._projectionMatrix;
  22824. };
  22825. Camera.prototype.getTranformationMatrix = function () {
  22826. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22827. return this._transformMatrix;
  22828. };
  22829. Camera.prototype.updateFrustumPlanes = function () {
  22830. if (!this._refreshFrustumPlanes) {
  22831. return;
  22832. }
  22833. this.getTranformationMatrix();
  22834. if (!this._frustumPlanes) {
  22835. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22836. }
  22837. else {
  22838. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22839. }
  22840. this._refreshFrustumPlanes = false;
  22841. };
  22842. Camera.prototype.isInFrustum = function (target) {
  22843. this.updateFrustumPlanes();
  22844. return target.isInFrustum(this._frustumPlanes);
  22845. };
  22846. Camera.prototype.isCompletelyInFrustum = function (target) {
  22847. this.updateFrustumPlanes();
  22848. return target.isCompletelyInFrustum(this._frustumPlanes);
  22849. };
  22850. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22851. if (length === void 0) { length = 100; }
  22852. if (!transform) {
  22853. transform = this.getWorldMatrix();
  22854. }
  22855. if (!origin) {
  22856. origin = this.position;
  22857. }
  22858. var forward = new BABYLON.Vector3(0, 0, 1);
  22859. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22860. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22861. return new BABYLON.Ray(origin, direction, length);
  22862. };
  22863. /**
  22864. * Releases resources associated with this node.
  22865. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22866. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22867. */
  22868. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22869. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22870. // Observables
  22871. this.onViewMatrixChangedObservable.clear();
  22872. this.onProjectionMatrixChangedObservable.clear();
  22873. this.onAfterCheckInputsObservable.clear();
  22874. this.onRestoreStateObservable.clear();
  22875. // Inputs
  22876. if (this.inputs) {
  22877. this.inputs.clear();
  22878. }
  22879. // Animations
  22880. this.getScene().stopAnimation(this);
  22881. // Remove from scene
  22882. this.getScene().removeCamera(this);
  22883. while (this._rigCameras.length > 0) {
  22884. var camera = this._rigCameras.pop();
  22885. if (camera) {
  22886. camera.dispose();
  22887. }
  22888. }
  22889. // Postprocesses
  22890. if (this._rigPostProcess) {
  22891. this._rigPostProcess.dispose(this);
  22892. this._rigPostProcess = null;
  22893. this._postProcesses = [];
  22894. }
  22895. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22896. this._rigPostProcess = null;
  22897. this._postProcesses = [];
  22898. }
  22899. else {
  22900. var i = this._postProcesses.length;
  22901. while (--i >= 0) {
  22902. var postProcess = this._postProcesses[i];
  22903. if (postProcess) {
  22904. postProcess.dispose(this);
  22905. }
  22906. }
  22907. }
  22908. // Render targets
  22909. var i = this.customRenderTargets.length;
  22910. while (--i >= 0) {
  22911. this.customRenderTargets[i].dispose();
  22912. }
  22913. this.customRenderTargets = [];
  22914. // Active Meshes
  22915. this._activeMeshes.dispose();
  22916. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22917. };
  22918. Object.defineProperty(Camera.prototype, "leftCamera", {
  22919. // ---- Camera rigs section ----
  22920. get: function () {
  22921. if (this._rigCameras.length < 1) {
  22922. return null;
  22923. }
  22924. return this._rigCameras[0];
  22925. },
  22926. enumerable: true,
  22927. configurable: true
  22928. });
  22929. Object.defineProperty(Camera.prototype, "rightCamera", {
  22930. get: function () {
  22931. if (this._rigCameras.length < 2) {
  22932. return null;
  22933. }
  22934. return this._rigCameras[1];
  22935. },
  22936. enumerable: true,
  22937. configurable: true
  22938. });
  22939. Camera.prototype.getLeftTarget = function () {
  22940. if (this._rigCameras.length < 1) {
  22941. return null;
  22942. }
  22943. return this._rigCameras[0].getTarget();
  22944. };
  22945. Camera.prototype.getRightTarget = function () {
  22946. if (this._rigCameras.length < 2) {
  22947. return null;
  22948. }
  22949. return this._rigCameras[1].getTarget();
  22950. };
  22951. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22952. if (this.cameraRigMode === mode) {
  22953. return;
  22954. }
  22955. while (this._rigCameras.length > 0) {
  22956. var camera = this._rigCameras.pop();
  22957. if (camera) {
  22958. camera.dispose();
  22959. }
  22960. }
  22961. this.cameraRigMode = mode;
  22962. this._cameraRigParams = {};
  22963. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22964. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22965. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22966. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22967. // create the rig cameras, unless none
  22968. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22969. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22970. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22971. if (leftCamera && rightCamera) {
  22972. this._rigCameras.push(leftCamera);
  22973. this._rigCameras.push(rightCamera);
  22974. }
  22975. }
  22976. switch (this.cameraRigMode) {
  22977. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22978. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22979. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22980. break;
  22981. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22982. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22983. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22984. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22985. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22986. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22987. break;
  22988. case Camera.RIG_MODE_VR:
  22989. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22990. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22991. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22992. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22993. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22994. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22995. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22996. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22997. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22998. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22999. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23000. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23001. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23002. if (metrics.compensateDistortion) {
  23003. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23004. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23005. }
  23006. break;
  23007. case Camera.RIG_MODE_WEBVR:
  23008. if (rigParams.vrDisplay) {
  23009. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23010. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23011. //Left eye
  23012. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23013. this._rigCameras[0].setCameraRigParameter("left", true);
  23014. //leaving this for future reference
  23015. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23016. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23017. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23018. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23019. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23020. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23021. this._rigCameras[0].parent = this;
  23022. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23023. //Right eye
  23024. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23025. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23026. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23027. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23028. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23029. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23030. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23031. this._rigCameras[1].parent = this;
  23032. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23033. if (Camera.UseAlternateWebVRRendering) {
  23034. this._rigCameras[1]._skipRendering = true;
  23035. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23036. }
  23037. }
  23038. break;
  23039. }
  23040. this._cascadePostProcessesToRigCams();
  23041. this.update();
  23042. };
  23043. Camera.prototype._getVRProjectionMatrix = function () {
  23044. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23045. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23046. return this._projectionMatrix;
  23047. };
  23048. Camera.prototype._updateCameraRotationMatrix = function () {
  23049. //Here for WebVR
  23050. };
  23051. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23052. //Here for WebVR
  23053. };
  23054. /**
  23055. * This function MUST be overwritten by the different WebVR cameras available.
  23056. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23057. */
  23058. Camera.prototype._getWebVRProjectionMatrix = function () {
  23059. return BABYLON.Matrix.Identity();
  23060. };
  23061. /**
  23062. * This function MUST be overwritten by the different WebVR cameras available.
  23063. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23064. */
  23065. Camera.prototype._getWebVRViewMatrix = function () {
  23066. return BABYLON.Matrix.Identity();
  23067. };
  23068. Camera.prototype.setCameraRigParameter = function (name, value) {
  23069. if (!this._cameraRigParams) {
  23070. this._cameraRigParams = {};
  23071. }
  23072. this._cameraRigParams[name] = value;
  23073. //provisionnally:
  23074. if (name === "interaxialDistance") {
  23075. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23076. }
  23077. };
  23078. /**
  23079. * needs to be overridden by children so sub has required properties to be copied
  23080. */
  23081. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23082. return null;
  23083. };
  23084. /**
  23085. * May need to be overridden by children
  23086. */
  23087. Camera.prototype._updateRigCameras = function () {
  23088. for (var i = 0; i < this._rigCameras.length; i++) {
  23089. this._rigCameras[i].minZ = this.minZ;
  23090. this._rigCameras[i].maxZ = this.maxZ;
  23091. this._rigCameras[i].fov = this.fov;
  23092. }
  23093. // only update viewport when ANAGLYPH
  23094. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23095. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23096. }
  23097. };
  23098. Camera.prototype._setupInputs = function () {
  23099. };
  23100. Camera.prototype.serialize = function () {
  23101. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23102. // Type
  23103. serializationObject.type = this.getClassName();
  23104. // Parent
  23105. if (this.parent) {
  23106. serializationObject.parentId = this.parent.id;
  23107. }
  23108. if (this.inputs) {
  23109. this.inputs.serialize(serializationObject);
  23110. }
  23111. // Animations
  23112. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23113. serializationObject.ranges = this.serializeAnimationRanges();
  23114. return serializationObject;
  23115. };
  23116. Camera.prototype.clone = function (name) {
  23117. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23118. };
  23119. Camera.prototype.getDirection = function (localAxis) {
  23120. var result = BABYLON.Vector3.Zero();
  23121. this.getDirectionToRef(localAxis, result);
  23122. return result;
  23123. };
  23124. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23125. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23126. };
  23127. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23128. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23129. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23130. switch (type) {
  23131. case "ArcRotateCamera":
  23132. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23133. case "DeviceOrientationCamera":
  23134. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23135. case "FollowCamera":
  23136. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23137. case "ArcFollowCamera":
  23138. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23139. case "GamepadCamera":
  23140. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23141. case "TouchCamera":
  23142. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23143. case "VirtualJoysticksCamera":
  23144. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23145. case "WebVRFreeCamera":
  23146. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23147. case "WebVRGamepadCamera":
  23148. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23149. case "VRDeviceOrientationFreeCamera":
  23150. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23151. case "VRDeviceOrientationGamepadCamera":
  23152. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23153. case "AnaglyphArcRotateCamera":
  23154. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23155. case "AnaglyphFreeCamera":
  23156. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23157. case "AnaglyphGamepadCamera":
  23158. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23159. case "AnaglyphUniversalCamera":
  23160. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23161. case "StereoscopicArcRotateCamera":
  23162. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23163. case "StereoscopicFreeCamera":
  23164. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23165. case "StereoscopicGamepadCamera":
  23166. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23167. case "StereoscopicUniversalCamera":
  23168. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23169. case "FreeCamera": // Forcing Universal here
  23170. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23171. default: // Universal Camera is the default value
  23172. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23173. }
  23174. };
  23175. Camera.prototype.computeWorldMatrix = function () {
  23176. return this.getWorldMatrix();
  23177. };
  23178. Camera.Parse = function (parsedCamera, scene) {
  23179. var type = parsedCamera.type;
  23180. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23181. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23182. // Parent
  23183. if (parsedCamera.parentId) {
  23184. camera._waitingParentId = parsedCamera.parentId;
  23185. }
  23186. //If camera has an input manager, let it parse inputs settings
  23187. if (camera.inputs) {
  23188. camera.inputs.parse(parsedCamera);
  23189. camera._setupInputs();
  23190. }
  23191. if (camera.setPosition) { // need to force position
  23192. camera.position.copyFromFloats(0, 0, 0);
  23193. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23194. }
  23195. // Target
  23196. if (parsedCamera.target) {
  23197. if (camera.setTarget) {
  23198. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23199. }
  23200. }
  23201. // Apply 3d rig, when found
  23202. if (parsedCamera.cameraRigMode) {
  23203. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23204. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23205. }
  23206. // Animations
  23207. if (parsedCamera.animations) {
  23208. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23209. var parsedAnimation = parsedCamera.animations[animationIndex];
  23210. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23211. }
  23212. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23213. }
  23214. if (parsedCamera.autoAnimate) {
  23215. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23216. }
  23217. return camera;
  23218. };
  23219. // Statics
  23220. Camera._PERSPECTIVE_CAMERA = 0;
  23221. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23222. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23223. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23224. Camera._RIG_MODE_NONE = 0;
  23225. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23226. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23227. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23228. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23229. Camera._RIG_MODE_VR = 20;
  23230. Camera._RIG_MODE_WEBVR = 21;
  23231. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23232. Camera.UseAlternateWebVRRendering = false;
  23233. __decorate([
  23234. BABYLON.serializeAsVector3()
  23235. ], Camera.prototype, "position", void 0);
  23236. __decorate([
  23237. BABYLON.serializeAsVector3()
  23238. ], Camera.prototype, "upVector", void 0);
  23239. __decorate([
  23240. BABYLON.serialize()
  23241. ], Camera.prototype, "orthoLeft", void 0);
  23242. __decorate([
  23243. BABYLON.serialize()
  23244. ], Camera.prototype, "orthoRight", void 0);
  23245. __decorate([
  23246. BABYLON.serialize()
  23247. ], Camera.prototype, "orthoBottom", void 0);
  23248. __decorate([
  23249. BABYLON.serialize()
  23250. ], Camera.prototype, "orthoTop", void 0);
  23251. __decorate([
  23252. BABYLON.serialize()
  23253. ], Camera.prototype, "fov", void 0);
  23254. __decorate([
  23255. BABYLON.serialize()
  23256. ], Camera.prototype, "minZ", void 0);
  23257. __decorate([
  23258. BABYLON.serialize()
  23259. ], Camera.prototype, "maxZ", void 0);
  23260. __decorate([
  23261. BABYLON.serialize()
  23262. ], Camera.prototype, "inertia", void 0);
  23263. __decorate([
  23264. BABYLON.serialize()
  23265. ], Camera.prototype, "mode", void 0);
  23266. __decorate([
  23267. BABYLON.serialize()
  23268. ], Camera.prototype, "layerMask", void 0);
  23269. __decorate([
  23270. BABYLON.serialize()
  23271. ], Camera.prototype, "fovMode", void 0);
  23272. __decorate([
  23273. BABYLON.serialize()
  23274. ], Camera.prototype, "cameraRigMode", void 0);
  23275. __decorate([
  23276. BABYLON.serialize()
  23277. ], Camera.prototype, "interaxialDistance", void 0);
  23278. __decorate([
  23279. BABYLON.serialize()
  23280. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23281. return Camera;
  23282. }(BABYLON.Node));
  23283. BABYLON.Camera = Camera;
  23284. })(BABYLON || (BABYLON = {}));
  23285. //# sourceMappingURL=babylon.camera.js.map
  23286. var BABYLON;
  23287. (function (BABYLON) {
  23288. var RenderingManager = /** @class */ (function () {
  23289. function RenderingManager(scene) {
  23290. this._renderingGroups = new Array();
  23291. this._autoClearDepthStencil = {};
  23292. this._customOpaqueSortCompareFn = {};
  23293. this._customAlphaTestSortCompareFn = {};
  23294. this._customTransparentSortCompareFn = {};
  23295. this._renderinGroupInfo = null;
  23296. this._scene = scene;
  23297. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23298. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23299. }
  23300. }
  23301. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23302. if (depth === void 0) { depth = true; }
  23303. if (stencil === void 0) { stencil = true; }
  23304. if (this._depthStencilBufferAlreadyCleaned) {
  23305. return;
  23306. }
  23307. this._scene.getEngine().clear(null, false, depth, stencil);
  23308. this._depthStencilBufferAlreadyCleaned = true;
  23309. };
  23310. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23311. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23312. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23313. var info = null;
  23314. if (observable) {
  23315. if (!this._renderinGroupInfo) {
  23316. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23317. }
  23318. info = this._renderinGroupInfo;
  23319. info.scene = this._scene;
  23320. info.camera = this._scene.activeCamera;
  23321. }
  23322. // Dispatch sprites
  23323. if (renderSprites) {
  23324. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23325. var manager = this._scene.spriteManagers[index];
  23326. this.dispatchSprites(manager);
  23327. }
  23328. }
  23329. // Render
  23330. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23331. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23332. var renderingGroup = this._renderingGroups[index];
  23333. if (!renderingGroup && !observable)
  23334. continue;
  23335. var renderingGroupMask = 0;
  23336. // Fire PRECLEAR stage
  23337. if (observable && info) {
  23338. renderingGroupMask = Math.pow(2, index);
  23339. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23340. info.renderingGroupId = index;
  23341. observable.notifyObservers(info, renderingGroupMask);
  23342. }
  23343. // Clear depth/stencil if needed
  23344. if (RenderingManager.AUTOCLEAR) {
  23345. var autoClear = this._autoClearDepthStencil[index];
  23346. if (autoClear && autoClear.autoClear) {
  23347. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23348. }
  23349. }
  23350. if (observable && info) {
  23351. // Fire PREOPAQUE stage
  23352. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23353. observable.notifyObservers(info, renderingGroupMask);
  23354. // Fire PRETRANSPARENT stage
  23355. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23356. observable.notifyObservers(info, renderingGroupMask);
  23357. }
  23358. if (renderingGroup)
  23359. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23360. // Fire POSTTRANSPARENT stage
  23361. if (observable && info) {
  23362. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23363. observable.notifyObservers(info, renderingGroupMask);
  23364. }
  23365. }
  23366. };
  23367. RenderingManager.prototype.reset = function () {
  23368. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23369. var renderingGroup = this._renderingGroups[index];
  23370. if (renderingGroup) {
  23371. renderingGroup.prepare();
  23372. }
  23373. }
  23374. };
  23375. RenderingManager.prototype.dispose = function () {
  23376. this.freeRenderingGroups();
  23377. this._renderingGroups.length = 0;
  23378. };
  23379. /**
  23380. * Clear the info related to rendering groups preventing retention points during dispose.
  23381. */
  23382. RenderingManager.prototype.freeRenderingGroups = function () {
  23383. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23384. var renderingGroup = this._renderingGroups[index];
  23385. if (renderingGroup) {
  23386. renderingGroup.dispose();
  23387. }
  23388. }
  23389. };
  23390. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23391. if (this._renderingGroups[renderingGroupId] === undefined) {
  23392. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23393. }
  23394. };
  23395. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23396. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23397. this._prepareRenderingGroup(renderingGroupId);
  23398. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23399. };
  23400. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23401. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23402. this._prepareRenderingGroup(renderingGroupId);
  23403. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23404. };
  23405. /**
  23406. * @param subMesh The submesh to dispatch
  23407. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23408. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23409. */
  23410. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23411. if (mesh === undefined) {
  23412. mesh = subMesh.getMesh();
  23413. }
  23414. var renderingGroupId = mesh.renderingGroupId || 0;
  23415. this._prepareRenderingGroup(renderingGroupId);
  23416. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23417. };
  23418. /**
  23419. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23420. * This allowed control for front to back rendering or reversly depending of the special needs.
  23421. *
  23422. * @param renderingGroupId The rendering group id corresponding to its index
  23423. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23424. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23425. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23426. */
  23427. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23428. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23429. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23430. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23431. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23432. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23433. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23434. if (this._renderingGroups[renderingGroupId]) {
  23435. var group = this._renderingGroups[renderingGroupId];
  23436. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23437. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23438. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23439. }
  23440. };
  23441. /**
  23442. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23443. *
  23444. * @param renderingGroupId The rendering group id corresponding to its index
  23445. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23446. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23447. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23448. */
  23449. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23450. if (depth === void 0) { depth = true; }
  23451. if (stencil === void 0) { stencil = true; }
  23452. this._autoClearDepthStencil[renderingGroupId] = {
  23453. autoClear: autoClearDepthStencil,
  23454. depth: depth,
  23455. stencil: stencil
  23456. };
  23457. };
  23458. /**
  23459. * The max id used for rendering groups (not included)
  23460. */
  23461. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23462. /**
  23463. * The min id used for rendering groups (included)
  23464. */
  23465. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23466. /**
  23467. * Used to globally prevent autoclearing scenes.
  23468. */
  23469. RenderingManager.AUTOCLEAR = true;
  23470. return RenderingManager;
  23471. }());
  23472. BABYLON.RenderingManager = RenderingManager;
  23473. })(BABYLON || (BABYLON = {}));
  23474. //# sourceMappingURL=babylon.renderingManager.js.map
  23475. var BABYLON;
  23476. (function (BABYLON) {
  23477. var RenderingGroup = /** @class */ (function () {
  23478. /**
  23479. * Creates a new rendering group.
  23480. * @param index The rendering group index
  23481. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23482. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23483. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23484. */
  23485. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23486. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23487. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23488. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23489. this.index = index;
  23490. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23491. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23492. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23493. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23494. this._particleSystems = new BABYLON.SmartArray(256);
  23495. this._spriteManagers = new BABYLON.SmartArray(256);
  23496. this._edgesRenderers = new BABYLON.SmartArray(16);
  23497. this._scene = scene;
  23498. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23499. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23500. this.transparentSortCompareFn = transparentSortCompareFn;
  23501. }
  23502. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23503. /**
  23504. * Set the opaque sort comparison function.
  23505. * If null the sub meshes will be render in the order they were created
  23506. */
  23507. set: function (value) {
  23508. this._opaqueSortCompareFn = value;
  23509. if (value) {
  23510. this._renderOpaque = this.renderOpaqueSorted;
  23511. }
  23512. else {
  23513. this._renderOpaque = RenderingGroup.renderUnsorted;
  23514. }
  23515. },
  23516. enumerable: true,
  23517. configurable: true
  23518. });
  23519. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23520. /**
  23521. * Set the alpha test sort comparison function.
  23522. * If null the sub meshes will be render in the order they were created
  23523. */
  23524. set: function (value) {
  23525. this._alphaTestSortCompareFn = value;
  23526. if (value) {
  23527. this._renderAlphaTest = this.renderAlphaTestSorted;
  23528. }
  23529. else {
  23530. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23531. }
  23532. },
  23533. enumerable: true,
  23534. configurable: true
  23535. });
  23536. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23537. /**
  23538. * Set the transparent sort comparison function.
  23539. * If null the sub meshes will be render in the order they were created
  23540. */
  23541. set: function (value) {
  23542. if (value) {
  23543. this._transparentSortCompareFn = value;
  23544. }
  23545. else {
  23546. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23547. }
  23548. this._renderTransparent = this.renderTransparentSorted;
  23549. },
  23550. enumerable: true,
  23551. configurable: true
  23552. });
  23553. /**
  23554. * Render all the sub meshes contained in the group.
  23555. * @param customRenderFunction Used to override the default render behaviour of the group.
  23556. * @returns true if rendered some submeshes.
  23557. */
  23558. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23559. if (customRenderFunction) {
  23560. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23561. return;
  23562. }
  23563. var engine = this._scene.getEngine();
  23564. // Depth only
  23565. if (this._depthOnlySubMeshes.length !== 0) {
  23566. engine.setColorWrite(false);
  23567. this._renderAlphaTest(this._depthOnlySubMeshes);
  23568. engine.setColorWrite(true);
  23569. }
  23570. // Opaque
  23571. if (this._opaqueSubMeshes.length !== 0) {
  23572. this._renderOpaque(this._opaqueSubMeshes);
  23573. }
  23574. // Alpha test
  23575. if (this._alphaTestSubMeshes.length !== 0) {
  23576. this._renderAlphaTest(this._alphaTestSubMeshes);
  23577. }
  23578. var stencilState = engine.getStencilBuffer();
  23579. engine.setStencilBuffer(false);
  23580. // Sprites
  23581. if (renderSprites) {
  23582. this._renderSprites();
  23583. }
  23584. // Particles
  23585. if (renderParticles) {
  23586. this._renderParticles(activeMeshes);
  23587. }
  23588. if (this.onBeforeTransparentRendering) {
  23589. this.onBeforeTransparentRendering();
  23590. }
  23591. // Transparent
  23592. if (this._transparentSubMeshes.length !== 0) {
  23593. this._renderTransparent(this._transparentSubMeshes);
  23594. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23595. }
  23596. // Set back stencil to false in case it changes before the edge renderer.
  23597. engine.setStencilBuffer(false);
  23598. // Edges
  23599. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23600. this._edgesRenderers.data[edgesRendererIndex].render();
  23601. }
  23602. // Restore Stencil state.
  23603. engine.setStencilBuffer(stencilState);
  23604. };
  23605. /**
  23606. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23607. * @param subMeshes The submeshes to render
  23608. */
  23609. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23610. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23611. };
  23612. /**
  23613. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23614. * @param subMeshes The submeshes to render
  23615. */
  23616. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23617. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23618. };
  23619. /**
  23620. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23621. * @param subMeshes The submeshes to render
  23622. */
  23623. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23624. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23625. };
  23626. /**
  23627. * Renders the submeshes in a specified order.
  23628. * @param subMeshes The submeshes to sort before render
  23629. * @param sortCompareFn The comparison function use to sort
  23630. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23631. * @param transparent Specifies to activate blending if true
  23632. */
  23633. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23634. var subIndex = 0;
  23635. var subMesh;
  23636. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23637. for (; subIndex < subMeshes.length; subIndex++) {
  23638. subMesh = subMeshes.data[subIndex];
  23639. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23640. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23641. }
  23642. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23643. if (sortCompareFn) {
  23644. sortedArray.sort(sortCompareFn);
  23645. }
  23646. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23647. subMesh = sortedArray[subIndex];
  23648. if (transparent) {
  23649. var material = subMesh.getMaterial();
  23650. if (material && material.needDepthPrePass) {
  23651. var engine = material.getScene().getEngine();
  23652. engine.setColorWrite(false);
  23653. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23654. subMesh.render(false);
  23655. engine.setColorWrite(true);
  23656. }
  23657. }
  23658. subMesh.render(transparent);
  23659. }
  23660. };
  23661. /**
  23662. * Renders the submeshes in the order they were dispatched (no sort applied).
  23663. * @param subMeshes The submeshes to render
  23664. */
  23665. RenderingGroup.renderUnsorted = function (subMeshes) {
  23666. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23667. var submesh = subMeshes.data[subIndex];
  23668. submesh.render(false);
  23669. }
  23670. };
  23671. /**
  23672. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23673. * are rendered back to front if in the same alpha index.
  23674. *
  23675. * @param a The first submesh
  23676. * @param b The second submesh
  23677. * @returns The result of the comparison
  23678. */
  23679. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23680. // Alpha index first
  23681. if (a._alphaIndex > b._alphaIndex) {
  23682. return 1;
  23683. }
  23684. if (a._alphaIndex < b._alphaIndex) {
  23685. return -1;
  23686. }
  23687. // Then distance to camera
  23688. return RenderingGroup.backToFrontSortCompare(a, b);
  23689. };
  23690. /**
  23691. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23692. * are rendered back to front.
  23693. *
  23694. * @param a The first submesh
  23695. * @param b The second submesh
  23696. * @returns The result of the comparison
  23697. */
  23698. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23699. // Then distance to camera
  23700. if (a._distanceToCamera < b._distanceToCamera) {
  23701. return 1;
  23702. }
  23703. if (a._distanceToCamera > b._distanceToCamera) {
  23704. return -1;
  23705. }
  23706. return 0;
  23707. };
  23708. /**
  23709. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23710. * are rendered front to back (prevent overdraw).
  23711. *
  23712. * @param a The first submesh
  23713. * @param b The second submesh
  23714. * @returns The result of the comparison
  23715. */
  23716. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23717. // Then distance to camera
  23718. if (a._distanceToCamera < b._distanceToCamera) {
  23719. return -1;
  23720. }
  23721. if (a._distanceToCamera > b._distanceToCamera) {
  23722. return 1;
  23723. }
  23724. return 0;
  23725. };
  23726. /**
  23727. * Resets the different lists of submeshes to prepare a new frame.
  23728. */
  23729. RenderingGroup.prototype.prepare = function () {
  23730. this._opaqueSubMeshes.reset();
  23731. this._transparentSubMeshes.reset();
  23732. this._alphaTestSubMeshes.reset();
  23733. this._depthOnlySubMeshes.reset();
  23734. this._particleSystems.reset();
  23735. this._spriteManagers.reset();
  23736. this._edgesRenderers.reset();
  23737. };
  23738. RenderingGroup.prototype.dispose = function () {
  23739. this._opaqueSubMeshes.dispose();
  23740. this._transparentSubMeshes.dispose();
  23741. this._alphaTestSubMeshes.dispose();
  23742. this._depthOnlySubMeshes.dispose();
  23743. this._particleSystems.dispose();
  23744. this._spriteManagers.dispose();
  23745. this._edgesRenderers.dispose();
  23746. };
  23747. /**
  23748. * Inserts the submesh in its correct queue depending on its material.
  23749. * @param subMesh The submesh to dispatch
  23750. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23751. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23752. */
  23753. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23754. // Get mesh and materials if not provided
  23755. if (mesh === undefined) {
  23756. mesh = subMesh.getMesh();
  23757. }
  23758. if (material === undefined) {
  23759. material = subMesh.getMaterial();
  23760. }
  23761. if (material === null || material === undefined) {
  23762. return;
  23763. }
  23764. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23765. this._transparentSubMeshes.push(subMesh);
  23766. }
  23767. else if (material.needAlphaTesting()) { // Alpha test
  23768. if (material.needDepthPrePass) {
  23769. this._depthOnlySubMeshes.push(subMesh);
  23770. }
  23771. this._alphaTestSubMeshes.push(subMesh);
  23772. }
  23773. else {
  23774. if (material.needDepthPrePass) {
  23775. this._depthOnlySubMeshes.push(subMesh);
  23776. }
  23777. this._opaqueSubMeshes.push(subMesh); // Opaque
  23778. }
  23779. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23780. this._edgesRenderers.push(mesh._edgesRenderer);
  23781. }
  23782. };
  23783. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23784. this._spriteManagers.push(spriteManager);
  23785. };
  23786. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23787. this._particleSystems.push(particleSystem);
  23788. };
  23789. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23790. if (this._particleSystems.length === 0) {
  23791. return;
  23792. }
  23793. // Particles
  23794. var activeCamera = this._scene.activeCamera;
  23795. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23796. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23797. var particleSystem = this._particleSystems.data[particleIndex];
  23798. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23799. continue;
  23800. }
  23801. var emitter = particleSystem.emitter;
  23802. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23803. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23804. }
  23805. }
  23806. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23807. };
  23808. RenderingGroup.prototype._renderSprites = function () {
  23809. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23810. return;
  23811. }
  23812. // Sprites
  23813. var activeCamera = this._scene.activeCamera;
  23814. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23815. for (var id = 0; id < this._spriteManagers.length; id++) {
  23816. var spriteManager = this._spriteManagers.data[id];
  23817. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23818. spriteManager.render();
  23819. }
  23820. }
  23821. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23822. };
  23823. return RenderingGroup;
  23824. }());
  23825. BABYLON.RenderingGroup = RenderingGroup;
  23826. })(BABYLON || (BABYLON = {}));
  23827. //# sourceMappingURL=babylon.renderingGroup.js.map
  23828. var BABYLON;
  23829. (function (BABYLON) {
  23830. /**
  23831. * Groups all the scene component constants in one place to ease maintenance.
  23832. * @hidden
  23833. */
  23834. var SceneComponentConstants = /** @class */ (function () {
  23835. function SceneComponentConstants() {
  23836. }
  23837. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  23838. SceneComponentConstants.NAME_LAYER = "Layer";
  23839. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  23840. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  23841. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  23842. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  23843. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  23844. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  23845. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  23846. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  23847. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  23848. return SceneComponentConstants;
  23849. }());
  23850. BABYLON.SceneComponentConstants = SceneComponentConstants;
  23851. /**
  23852. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  23853. * @hidden
  23854. */
  23855. var Stage = /** @class */ (function (_super) {
  23856. __extends(Stage, _super);
  23857. /**
  23858. * Hide ctor from the rest of the world.
  23859. * @param items The items to add.
  23860. */
  23861. function Stage(items) {
  23862. return _super.apply(this, items) || this;
  23863. }
  23864. /**
  23865. * Creates a new Stage.
  23866. * @returns A new instance of a Stage
  23867. */
  23868. Stage.Create = function () {
  23869. return Object.create(Stage.prototype);
  23870. };
  23871. /**
  23872. * Registers a step in an ordered way in the targeted stage.
  23873. * @param index Defines the position to register the step in
  23874. * @param component Defines the component attached to the step
  23875. * @param action Defines the action to launch during the step
  23876. */
  23877. Stage.prototype.registerStep = function (index, component, action) {
  23878. var i = 0;
  23879. var maxIndex = Number.MAX_VALUE;
  23880. for (; i < this.length && i < maxIndex; i++) {
  23881. var step = this[i];
  23882. maxIndex = step.index;
  23883. }
  23884. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  23885. };
  23886. /**
  23887. * Clears all the steps from the stage.
  23888. */
  23889. Stage.prototype.clear = function () {
  23890. this.length = 0;
  23891. };
  23892. return Stage;
  23893. }(Array));
  23894. BABYLON.Stage = Stage;
  23895. })(BABYLON || (BABYLON = {}));
  23896. //# sourceMappingURL=babylon.sceneComponent.js.map
  23897. var BABYLON;
  23898. (function (BABYLON) {
  23899. /**
  23900. * Base class of the scene acting as a container for the different elements composing a scene.
  23901. * This class is dynamically extended by the different components of the scene increasing
  23902. * flexibility and reducing coupling.
  23903. */
  23904. var AbstractScene = /** @class */ (function () {
  23905. function AbstractScene() {
  23906. /** All of the cameras added to this scene
  23907. * @see http://doc.babylonjs.com/babylon101/cameras
  23908. */
  23909. this.cameras = new Array();
  23910. /**
  23911. * All of the lights added to this scene
  23912. * @see http://doc.babylonjs.com/babylon101/lights
  23913. */
  23914. this.lights = new Array();
  23915. /**
  23916. * All of the (abstract) meshes added to this scene
  23917. */
  23918. this.meshes = new Array();
  23919. /**
  23920. * The list of skeletons added to the scene
  23921. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23922. */
  23923. this.skeletons = new Array();
  23924. /**
  23925. * All of the particle systems added to this scene
  23926. * @see http://doc.babylonjs.com/babylon101/particles
  23927. */
  23928. this.particleSystems = new Array();
  23929. /**
  23930. * Gets a list of Animations associated with the scene
  23931. */
  23932. this.animations = [];
  23933. /**
  23934. * All of the animation groups added to this scene
  23935. * @see http://doc.babylonjs.com/how_to/group
  23936. */
  23937. this.animationGroups = new Array();
  23938. /**
  23939. * All of the multi-materials added to this scene
  23940. * @see http://doc.babylonjs.com/how_to/multi_materials
  23941. */
  23942. this.multiMaterials = new Array();
  23943. /**
  23944. * All of the materials added to this scene
  23945. * @see http://doc.babylonjs.com/babylon101/materials
  23946. */
  23947. this.materials = new Array();
  23948. /**
  23949. * The list of morph target managers added to the scene
  23950. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23951. */
  23952. this.morphTargetManagers = new Array();
  23953. /**
  23954. * The list of geometries used in the scene.
  23955. */
  23956. this.geometries = new Array();
  23957. /**
  23958. * All of the tranform nodes added to this scene
  23959. * @see http://doc.babylonjs.com/how_to/transformnode
  23960. */
  23961. this.transformNodes = new Array();
  23962. /**
  23963. * ActionManagers available on the scene.
  23964. */
  23965. this.actionManagers = new Array();
  23966. /**
  23967. * Sounds to keep.
  23968. */
  23969. this.sounds = new Array();
  23970. /**
  23971. * Textures to keep.
  23972. */
  23973. this.textures = new Array();
  23974. }
  23975. /**
  23976. * Adds a parser in the list of availables ones.
  23977. * @param name Defines the name of the parser
  23978. * @param parser Defines the parser to add
  23979. */
  23980. AbstractScene.AddParser = function (name, parser) {
  23981. this._BabylonFileParsers[name] = parser;
  23982. };
  23983. /**
  23984. * Parser json data and populate both a scene and its associated container object
  23985. * @param jsonData Defines the data to parse
  23986. * @param scene Defines the scene to parse the data for
  23987. * @param container Defines the container attached to the parsing sequence
  23988. * @param rootUrl Defines the root url of the data
  23989. */
  23990. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  23991. for (var parserName in this._BabylonFileParsers) {
  23992. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  23993. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  23994. }
  23995. }
  23996. };
  23997. /**
  23998. * Stores the list of available parsers in the application.
  23999. */
  24000. AbstractScene._BabylonFileParsers = {};
  24001. return AbstractScene;
  24002. }());
  24003. BABYLON.AbstractScene = AbstractScene;
  24004. })(BABYLON || (BABYLON = {}));
  24005. //# sourceMappingURL=babylon.abstractScene.js.map
  24006. var BABYLON;
  24007. (function (BABYLON) {
  24008. /** @hidden */
  24009. var ClickInfo = /** @class */ (function () {
  24010. function ClickInfo() {
  24011. this._singleClick = false;
  24012. this._doubleClick = false;
  24013. this._hasSwiped = false;
  24014. this._ignore = false;
  24015. }
  24016. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  24017. get: function () {
  24018. return this._singleClick;
  24019. },
  24020. set: function (b) {
  24021. this._singleClick = b;
  24022. },
  24023. enumerable: true,
  24024. configurable: true
  24025. });
  24026. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  24027. get: function () {
  24028. return this._doubleClick;
  24029. },
  24030. set: function (b) {
  24031. this._doubleClick = b;
  24032. },
  24033. enumerable: true,
  24034. configurable: true
  24035. });
  24036. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  24037. get: function () {
  24038. return this._hasSwiped;
  24039. },
  24040. set: function (b) {
  24041. this._hasSwiped = b;
  24042. },
  24043. enumerable: true,
  24044. configurable: true
  24045. });
  24046. Object.defineProperty(ClickInfo.prototype, "ignore", {
  24047. get: function () {
  24048. return this._ignore;
  24049. },
  24050. set: function (b) {
  24051. this._ignore = b;
  24052. },
  24053. enumerable: true,
  24054. configurable: true
  24055. });
  24056. return ClickInfo;
  24057. }());
  24058. /**
  24059. * This class is used by the onRenderingGroupObservable
  24060. */
  24061. var RenderingGroupInfo = /** @class */ (function () {
  24062. function RenderingGroupInfo() {
  24063. }
  24064. /**
  24065. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  24066. * This stage will be fired no matter what
  24067. */
  24068. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  24069. /**
  24070. * Called before opaque object are rendered.
  24071. * This stage will be fired only if there's 3D Opaque content to render
  24072. */
  24073. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  24074. /**
  24075. * Called after the opaque objects are rendered and before the transparent ones
  24076. * This stage will be fired only if there's 3D transparent content to render
  24077. */
  24078. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  24079. /**
  24080. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  24081. * This stage will be fired no matter what
  24082. */
  24083. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  24084. return RenderingGroupInfo;
  24085. }());
  24086. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24087. /**
  24088. * Represents a scene to be rendered by the engine.
  24089. * @see http://doc.babylonjs.com/features/scene
  24090. */
  24091. var Scene = /** @class */ (function (_super) {
  24092. __extends(Scene, _super);
  24093. /**
  24094. * Creates a new Scene
  24095. * @param engine defines the engine to use to render this scene
  24096. */
  24097. function Scene(engine) {
  24098. var _this = _super.call(this) || this;
  24099. // Members
  24100. /**
  24101. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24102. */
  24103. _this.autoClear = true;
  24104. /**
  24105. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24106. */
  24107. _this.autoClearDepthAndStencil = true;
  24108. /**
  24109. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24110. */
  24111. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24112. /**
  24113. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24114. */
  24115. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24116. _this._forceWireframe = false;
  24117. _this._forcePointsCloud = false;
  24118. /**
  24119. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  24120. */
  24121. _this.forceShowBoundingBoxes = false;
  24122. /**
  24123. * Gets or sets a boolean indicating if animations are enabled
  24124. */
  24125. _this.animationsEnabled = true;
  24126. _this._animationPropertiesOverride = null;
  24127. /**
  24128. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24129. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24130. */
  24131. _this.useConstantAnimationDeltaTime = false;
  24132. /**
  24133. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24134. * Please note that it requires to run a ray cast through the scene on every frame
  24135. */
  24136. _this.constantlyUpdateMeshUnderPointer = false;
  24137. /**
  24138. * Defines the HTML cursor to use when hovering over interactive elements
  24139. */
  24140. _this.hoverCursor = "pointer";
  24141. /**
  24142. * Defines the HTML default cursor to use (empty by default)
  24143. */
  24144. _this.defaultCursor = "";
  24145. /**
  24146. * This is used to call preventDefault() on pointer down
  24147. * in order to block unwanted artifacts like system double clicks
  24148. */
  24149. _this.preventDefaultOnPointerDown = true;
  24150. // Metadata
  24151. /**
  24152. * Gets or sets user defined metadata
  24153. */
  24154. _this.metadata = null;
  24155. /**
  24156. * Use this array to add regular expressions used to disable offline support for specific urls
  24157. */
  24158. _this.disableOfflineSupportExceptionRules = new Array();
  24159. /**
  24160. * An event triggered when the scene is disposed.
  24161. */
  24162. _this.onDisposeObservable = new BABYLON.Observable();
  24163. _this._onDisposeObserver = null;
  24164. /**
  24165. * An event triggered before rendering the scene (right after animations and physics)
  24166. */
  24167. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24168. _this._onBeforeRenderObserver = null;
  24169. /**
  24170. * An event triggered after rendering the scene
  24171. */
  24172. _this.onAfterRenderObservable = new BABYLON.Observable();
  24173. _this._onAfterRenderObserver = null;
  24174. /**
  24175. * An event triggered before animating the scene
  24176. */
  24177. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24178. /**
  24179. * An event triggered after animations processing
  24180. */
  24181. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  24182. /**
  24183. * An event triggered before draw calls are ready to be sent
  24184. */
  24185. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24186. /**
  24187. * An event triggered after draw calls have been sent
  24188. */
  24189. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24190. /**
  24191. * An event triggered when physic simulation is about to be run
  24192. */
  24193. _this.onBeforePhysicsObservable = new BABYLON.Observable();
  24194. /**
  24195. * An event triggered when physic simulation has been done
  24196. */
  24197. _this.onAfterPhysicsObservable = new BABYLON.Observable();
  24198. /**
  24199. * An event triggered when the scene is ready
  24200. */
  24201. _this.onReadyObservable = new BABYLON.Observable();
  24202. /**
  24203. * An event triggered before rendering a camera
  24204. */
  24205. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24206. _this._onBeforeCameraRenderObserver = null;
  24207. /**
  24208. * An event triggered after rendering a camera
  24209. */
  24210. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24211. _this._onAfterCameraRenderObserver = null;
  24212. /**
  24213. * An event triggered when active meshes evaluation is about to start
  24214. */
  24215. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24216. /**
  24217. * An event triggered when active meshes evaluation is done
  24218. */
  24219. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24220. /**
  24221. * An event triggered when particles rendering is about to start
  24222. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24223. */
  24224. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24225. /**
  24226. * An event triggered when particles rendering is done
  24227. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24228. */
  24229. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24230. /**
  24231. * An event triggered when sprites rendering is about to start
  24232. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24233. */
  24234. _this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24235. /**
  24236. * An event triggered when sprites rendering is done
  24237. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24238. */
  24239. _this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24240. /**
  24241. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24242. */
  24243. _this.onDataLoadedObservable = new BABYLON.Observable();
  24244. /**
  24245. * An event triggered when a camera is created
  24246. */
  24247. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  24248. /**
  24249. * An event triggered when a camera is removed
  24250. */
  24251. _this.onCameraRemovedObservable = new BABYLON.Observable();
  24252. /**
  24253. * An event triggered when a light is created
  24254. */
  24255. _this.onNewLightAddedObservable = new BABYLON.Observable();
  24256. /**
  24257. * An event triggered when a light is removed
  24258. */
  24259. _this.onLightRemovedObservable = new BABYLON.Observable();
  24260. /**
  24261. * An event triggered when a geometry is created
  24262. */
  24263. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24264. /**
  24265. * An event triggered when a geometry is removed
  24266. */
  24267. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  24268. /**
  24269. * An event triggered when a transform node is created
  24270. */
  24271. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24272. /**
  24273. * An event triggered when a transform node is removed
  24274. */
  24275. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24276. /**
  24277. * An event triggered when a mesh is created
  24278. */
  24279. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  24280. /**
  24281. * An event triggered when a mesh is removed
  24282. */
  24283. _this.onMeshRemovedObservable = new BABYLON.Observable();
  24284. /**
  24285. * An event triggered when render targets are about to be rendered
  24286. * Can happen multiple times per frame.
  24287. */
  24288. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24289. /**
  24290. * An event triggered when render targets were rendered.
  24291. * Can happen multiple times per frame.
  24292. */
  24293. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24294. /**
  24295. * An event triggered before calculating deterministic simulation step
  24296. */
  24297. _this.onBeforeStepObservable = new BABYLON.Observable();
  24298. /**
  24299. * An event triggered after calculating deterministic simulation step
  24300. */
  24301. _this.onAfterStepObservable = new BABYLON.Observable();
  24302. /**
  24303. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24304. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24305. * 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)
  24306. */
  24307. _this.onRenderingGroupObservable = new BABYLON.Observable();
  24308. // Animations
  24309. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24310. /**
  24311. * 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).
  24312. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24313. */
  24314. _this.onPrePointerObservable = new BABYLON.Observable();
  24315. /**
  24316. * Observable event triggered each time an input event is received from the rendering canvas
  24317. */
  24318. _this.onPointerObservable = new BABYLON.Observable();
  24319. _this._meshPickProceed = false;
  24320. _this._currentPickResult = null;
  24321. _this._previousPickResult = null;
  24322. _this._totalPointersPressed = 0;
  24323. _this._doubleClickOccured = false;
  24324. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24325. _this.cameraToUseForPointers = null;
  24326. _this._pointerX = 0;
  24327. _this._pointerY = 0;
  24328. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24329. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24330. _this._startingPointerTime = 0;
  24331. _this._previousStartingPointerTime = 0;
  24332. _this._pointerCaptures = {};
  24333. // Deterministic lockstep
  24334. _this._timeAccumulator = 0;
  24335. _this._currentStepId = 0;
  24336. _this._currentInternalStep = 0;
  24337. // Keyboard
  24338. /**
  24339. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24340. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24341. */
  24342. _this.onPreKeyboardObservable = new BABYLON.Observable();
  24343. /**
  24344. * Observable event triggered each time an keyboard event is received from the hosting window
  24345. */
  24346. _this.onKeyboardObservable = new BABYLON.Observable();
  24347. // Coordinates system
  24348. _this._useRightHandedSystem = false;
  24349. // Fog
  24350. _this._fogEnabled = true;
  24351. _this._fogMode = Scene.FOGMODE_NONE;
  24352. /**
  24353. * Gets or sets the fog color to use
  24354. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24355. */
  24356. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24357. /**
  24358. * Gets or sets the fog density to use
  24359. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24360. */
  24361. _this.fogDensity = 0.1;
  24362. /**
  24363. * Gets or sets the fog start distance to use
  24364. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24365. */
  24366. _this.fogStart = 0;
  24367. /**
  24368. * Gets or sets the fog end distance to use
  24369. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24370. */
  24371. _this.fogEnd = 1000.0;
  24372. // Lights
  24373. _this._shadowsEnabled = true;
  24374. _this._lightsEnabled = true;
  24375. /** All of the active cameras added to this scene. */
  24376. _this.activeCameras = new Array();
  24377. // Textures
  24378. _this._texturesEnabled = true;
  24379. // Particles
  24380. /**
  24381. * Gets or sets a boolean indicating if particles are enabled on this scene
  24382. */
  24383. _this.particlesEnabled = true;
  24384. // Sprites
  24385. /**
  24386. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24387. */
  24388. _this.spritesEnabled = true;
  24389. /**
  24390. * All of the sprite managers added to this scene
  24391. * @see http://doc.babylonjs.com/babylon101/sprites
  24392. */
  24393. _this.spriteManagers = new Array();
  24394. // Skeletons
  24395. _this._skeletonsEnabled = true;
  24396. // Lens flares
  24397. /**
  24398. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24399. */
  24400. _this.lensFlaresEnabled = true;
  24401. // Collisions
  24402. /**
  24403. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24404. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24405. */
  24406. _this.collisionsEnabled = true;
  24407. /**
  24408. * Defines the gravity applied to this scene (used only for collisions)
  24409. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24410. */
  24411. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24412. // Postprocesses
  24413. /**
  24414. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24415. */
  24416. _this.postProcessesEnabled = true;
  24417. /**
  24418. * The list of postprocesses added to the scene
  24419. */
  24420. _this.postProcesses = new Array();
  24421. // Customs render targets
  24422. /**
  24423. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24424. */
  24425. _this.renderTargetsEnabled = true;
  24426. /**
  24427. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24428. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24429. */
  24430. _this.dumpNextRenderTargets = false;
  24431. /**
  24432. * The list of user defined render targets added to the scene
  24433. */
  24434. _this.customRenderTargets = new Array();
  24435. /**
  24436. * Gets the list of meshes imported to the scene through SceneLoader
  24437. */
  24438. _this.importedMeshesFiles = new Array();
  24439. // Probes
  24440. /**
  24441. * Gets or sets a boolean indicating if probes are enabled on this scene
  24442. */
  24443. _this.probesEnabled = true;
  24444. /**
  24445. * The list of reflection probes added to the scene
  24446. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24447. */
  24448. _this.reflectionProbes = new Array();
  24449. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24450. // Procedural textures
  24451. /**
  24452. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24453. */
  24454. _this.proceduralTexturesEnabled = true;
  24455. /**
  24456. * The list of procedural textures added to the scene
  24457. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24458. */
  24459. _this.proceduralTextures = new Array();
  24460. /**
  24461. * The list of sound tracks added to the scene
  24462. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24463. */
  24464. _this.soundTracks = new Array();
  24465. _this._audioEnabled = true;
  24466. _this._headphone = false;
  24467. // Performance counters
  24468. _this._totalVertices = new BABYLON.PerfCounter();
  24469. /** @hidden */
  24470. _this._activeIndices = new BABYLON.PerfCounter();
  24471. /** @hidden */
  24472. _this._activeParticles = new BABYLON.PerfCounter();
  24473. /** @hidden */
  24474. _this._activeBones = new BABYLON.PerfCounter();
  24475. _this._animationTime = 0;
  24476. /**
  24477. * Gets or sets a general scale for animation speed
  24478. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24479. */
  24480. _this.animationTimeScale = 1;
  24481. _this._renderId = 0;
  24482. _this._executeWhenReadyTimeoutId = -1;
  24483. _this._intermediateRendering = false;
  24484. _this._viewUpdateFlag = -1;
  24485. _this._projectionUpdateFlag = -1;
  24486. _this._alternateViewUpdateFlag = -1;
  24487. _this._alternateProjectionUpdateFlag = -1;
  24488. /** @hidden */
  24489. _this._toBeDisposed = new BABYLON.SmartArray(256);
  24490. _this._activeRequests = new Array();
  24491. _this._pendingData = new Array();
  24492. _this._isDisposed = false;
  24493. /**
  24494. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24495. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24496. */
  24497. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  24498. _this._activeMeshes = new BABYLON.SmartArray(256);
  24499. _this._processedMaterials = new BABYLON.SmartArray(256);
  24500. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24501. /** @hidden */
  24502. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  24503. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24504. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24505. /** @hidden */
  24506. _this._activeAnimatables = new Array();
  24507. _this._transformMatrix = BABYLON.Matrix.Zero();
  24508. _this._useAlternateCameraConfiguration = false;
  24509. _this._alternateRendering = false;
  24510. /**
  24511. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24512. * This is useful if there are more lights that the maximum simulteanous authorized
  24513. */
  24514. _this.requireLightSorting = false;
  24515. _this._depthRenderer = {};
  24516. /**
  24517. * Backing store of defined scene components.
  24518. */
  24519. _this._components = [];
  24520. /**
  24521. * List of components to register on the next registration step.
  24522. */
  24523. _this._transientComponents = [];
  24524. /**
  24525. * Defines the actions happening during the per mesh ready checks.
  24526. */
  24527. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  24528. /**
  24529. * Defines the actions happening during the per camera render target step.
  24530. */
  24531. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  24532. /**
  24533. * Defines the actions happening just before the active camera is drawing.
  24534. */
  24535. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  24536. /**
  24537. * Defines the actions happening just after the active camera is drawing.
  24538. */
  24539. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  24540. _this._activeMeshesFrozen = false;
  24541. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24542. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24543. _this._engine.scenes.push(_this);
  24544. _this._uid = null;
  24545. _this._renderingManager = new BABYLON.RenderingManager(_this);
  24546. if (BABYLON.PostProcessManager) {
  24547. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  24548. }
  24549. if (BABYLON.OutlineRenderer) {
  24550. _this._outlineRenderer = new BABYLON.OutlineRenderer(_this);
  24551. }
  24552. if (BABYLON.Tools.IsWindowObjectExist()) {
  24553. _this.attachControl();
  24554. }
  24555. //simplification queue
  24556. if (BABYLON.SimplificationQueue) {
  24557. _this.simplificationQueue = new BABYLON.SimplificationQueue();
  24558. }
  24559. //collision coordinator initialization. For now legacy per default.
  24560. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24561. // Uniform Buffer
  24562. _this._createUbo();
  24563. // Default Image processing definition
  24564. if (BABYLON.ImageProcessingConfiguration) {
  24565. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24566. }
  24567. return _this;
  24568. }
  24569. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24570. /** The fog is deactivated */
  24571. get: function () {
  24572. return Scene._FOGMODE_NONE;
  24573. },
  24574. enumerable: true,
  24575. configurable: true
  24576. });
  24577. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24578. /** The fog density is following an exponential function */
  24579. get: function () {
  24580. return Scene._FOGMODE_EXP;
  24581. },
  24582. enumerable: true,
  24583. configurable: true
  24584. });
  24585. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24586. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24587. get: function () {
  24588. return Scene._FOGMODE_EXP2;
  24589. },
  24590. enumerable: true,
  24591. configurable: true
  24592. });
  24593. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24594. /** The fog density is following a linear function. */
  24595. get: function () {
  24596. return Scene._FOGMODE_LINEAR;
  24597. },
  24598. enumerable: true,
  24599. configurable: true
  24600. });
  24601. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24602. /**
  24603. * Texture used in all pbr material as the reflection texture.
  24604. * As in the majority of the scene they are the same (exception for multi room and so on),
  24605. * this is easier to reference from here than from all the materials.
  24606. */
  24607. get: function () {
  24608. return this._environmentTexture;
  24609. },
  24610. /**
  24611. * Texture used in all pbr material as the reflection texture.
  24612. * As in the majority of the scene they are the same (exception for multi room and so on),
  24613. * this is easier to set here than in all the materials.
  24614. */
  24615. set: function (value) {
  24616. if (this._environmentTexture === value) {
  24617. return;
  24618. }
  24619. this._environmentTexture = value;
  24620. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24621. },
  24622. enumerable: true,
  24623. configurable: true
  24624. });
  24625. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24626. /**
  24627. * Default image processing configuration used either in the rendering
  24628. * Forward main pass or through the imageProcessingPostProcess if present.
  24629. * As in the majority of the scene they are the same (exception for multi camera),
  24630. * this is easier to reference from here than from all the materials and post process.
  24631. *
  24632. * No setter as we it is a shared configuration, you can set the values instead.
  24633. */
  24634. get: function () {
  24635. return this._imageProcessingConfiguration;
  24636. },
  24637. enumerable: true,
  24638. configurable: true
  24639. });
  24640. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24641. get: function () {
  24642. return this._forceWireframe;
  24643. },
  24644. /**
  24645. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24646. */
  24647. set: function (value) {
  24648. if (this._forceWireframe === value) {
  24649. return;
  24650. }
  24651. this._forceWireframe = value;
  24652. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24653. },
  24654. enumerable: true,
  24655. configurable: true
  24656. });
  24657. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24658. get: function () {
  24659. return this._forcePointsCloud;
  24660. },
  24661. /**
  24662. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24663. */
  24664. set: function (value) {
  24665. if (this._forcePointsCloud === value) {
  24666. return;
  24667. }
  24668. this._forcePointsCloud = value;
  24669. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24670. },
  24671. enumerable: true,
  24672. configurable: true
  24673. });
  24674. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24675. /**
  24676. * Gets or sets the animation properties override
  24677. */
  24678. get: function () {
  24679. return this._animationPropertiesOverride;
  24680. },
  24681. set: function (value) {
  24682. this._animationPropertiesOverride = value;
  24683. },
  24684. enumerable: true,
  24685. configurable: true
  24686. });
  24687. Object.defineProperty(Scene.prototype, "onDispose", {
  24688. /** Sets a function to be executed when this scene is disposed. */
  24689. set: function (callback) {
  24690. if (this._onDisposeObserver) {
  24691. this.onDisposeObservable.remove(this._onDisposeObserver);
  24692. }
  24693. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24694. },
  24695. enumerable: true,
  24696. configurable: true
  24697. });
  24698. Object.defineProperty(Scene.prototype, "beforeRender", {
  24699. /** Sets a function to be executed before rendering this scene */
  24700. set: function (callback) {
  24701. if (this._onBeforeRenderObserver) {
  24702. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24703. }
  24704. if (callback) {
  24705. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24706. }
  24707. },
  24708. enumerable: true,
  24709. configurable: true
  24710. });
  24711. Object.defineProperty(Scene.prototype, "afterRender", {
  24712. /** Sets a function to be executed after rendering this scene */
  24713. set: function (callback) {
  24714. if (this._onAfterRenderObserver) {
  24715. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24716. }
  24717. if (callback) {
  24718. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24719. }
  24720. },
  24721. enumerable: true,
  24722. configurable: true
  24723. });
  24724. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24725. /** Sets a function to be executed before rendering a camera*/
  24726. set: function (callback) {
  24727. if (this._onBeforeCameraRenderObserver) {
  24728. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24729. }
  24730. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24731. },
  24732. enumerable: true,
  24733. configurable: true
  24734. });
  24735. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24736. /** Sets a function to be executed after rendering a camera*/
  24737. set: function (callback) {
  24738. if (this._onAfterCameraRenderObserver) {
  24739. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24740. }
  24741. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24742. },
  24743. enumerable: true,
  24744. configurable: true
  24745. });
  24746. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24747. /**
  24748. * Gets the gamepad manager associated with the scene
  24749. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24750. */
  24751. get: function () {
  24752. if (!this._gamepadManager) {
  24753. this._gamepadManager = new BABYLON.GamepadManager(this);
  24754. }
  24755. return this._gamepadManager;
  24756. },
  24757. enumerable: true,
  24758. configurable: true
  24759. });
  24760. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24761. /**
  24762. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24763. */
  24764. get: function () {
  24765. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24766. },
  24767. enumerable: true,
  24768. configurable: true
  24769. });
  24770. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24771. get: function () {
  24772. return this._useRightHandedSystem;
  24773. },
  24774. /**
  24775. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24776. */
  24777. set: function (value) {
  24778. if (this._useRightHandedSystem === value) {
  24779. return;
  24780. }
  24781. this._useRightHandedSystem = value;
  24782. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24783. },
  24784. enumerable: true,
  24785. configurable: true
  24786. });
  24787. /**
  24788. * Sets the step Id used by deterministic lock step
  24789. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24790. * @param newStepId defines the step Id
  24791. */
  24792. Scene.prototype.setStepId = function (newStepId) {
  24793. this._currentStepId = newStepId;
  24794. };
  24795. ;
  24796. /**
  24797. * Gets the step Id used by deterministic lock step
  24798. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24799. * @returns the step Id
  24800. */
  24801. Scene.prototype.getStepId = function () {
  24802. return this._currentStepId;
  24803. };
  24804. ;
  24805. /**
  24806. * Gets the internal step used by deterministic lock step
  24807. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24808. * @returns the internal step
  24809. */
  24810. Scene.prototype.getInternalStep = function () {
  24811. return this._currentInternalStep;
  24812. };
  24813. ;
  24814. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24815. get: function () {
  24816. return this._fogEnabled;
  24817. },
  24818. /**
  24819. * Gets or sets a boolean indicating if fog is enabled on this scene
  24820. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24821. */
  24822. set: function (value) {
  24823. if (this._fogEnabled === value) {
  24824. return;
  24825. }
  24826. this._fogEnabled = value;
  24827. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24828. },
  24829. enumerable: true,
  24830. configurable: true
  24831. });
  24832. Object.defineProperty(Scene.prototype, "fogMode", {
  24833. get: function () {
  24834. return this._fogMode;
  24835. },
  24836. /**
  24837. * Gets or sets the fog mode to use
  24838. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24839. */
  24840. set: function (value) {
  24841. if (this._fogMode === value) {
  24842. return;
  24843. }
  24844. this._fogMode = value;
  24845. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24846. },
  24847. enumerable: true,
  24848. configurable: true
  24849. });
  24850. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24851. get: function () {
  24852. return this._shadowsEnabled;
  24853. },
  24854. /**
  24855. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24856. */
  24857. set: function (value) {
  24858. if (this._shadowsEnabled === value) {
  24859. return;
  24860. }
  24861. this._shadowsEnabled = value;
  24862. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24863. },
  24864. enumerable: true,
  24865. configurable: true
  24866. });
  24867. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24868. get: function () {
  24869. return this._lightsEnabled;
  24870. },
  24871. /**
  24872. * Gets or sets a boolean indicating if lights are enabled on this scene
  24873. */
  24874. set: function (value) {
  24875. if (this._lightsEnabled === value) {
  24876. return;
  24877. }
  24878. this._lightsEnabled = value;
  24879. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24880. },
  24881. enumerable: true,
  24882. configurable: true
  24883. });
  24884. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24885. /** The default material used on meshes when no material is affected */
  24886. get: function () {
  24887. if (!this._defaultMaterial) {
  24888. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24889. }
  24890. return this._defaultMaterial;
  24891. },
  24892. /** The default material used on meshes when no material is affected */
  24893. set: function (value) {
  24894. this._defaultMaterial = value;
  24895. },
  24896. enumerable: true,
  24897. configurable: true
  24898. });
  24899. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24900. get: function () {
  24901. return this._texturesEnabled;
  24902. },
  24903. /**
  24904. * Gets or sets a boolean indicating if textures are enabled on this scene
  24905. */
  24906. set: function (value) {
  24907. if (this._texturesEnabled === value) {
  24908. return;
  24909. }
  24910. this._texturesEnabled = value;
  24911. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24912. },
  24913. enumerable: true,
  24914. configurable: true
  24915. });
  24916. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24917. get: function () {
  24918. return this._skeletonsEnabled;
  24919. },
  24920. /**
  24921. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24922. */
  24923. set: function (value) {
  24924. if (this._skeletonsEnabled === value) {
  24925. return;
  24926. }
  24927. this._skeletonsEnabled = value;
  24928. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24929. },
  24930. enumerable: true,
  24931. configurable: true
  24932. });
  24933. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24934. /**
  24935. * Gets the postprocess render pipeline manager
  24936. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24937. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24938. */
  24939. get: function () {
  24940. if (!this._postProcessRenderPipelineManager) {
  24941. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24942. }
  24943. return this._postProcessRenderPipelineManager;
  24944. },
  24945. enumerable: true,
  24946. configurable: true
  24947. });
  24948. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24949. /**
  24950. * Gets the main soundtrack associated with the scene
  24951. */
  24952. get: function () {
  24953. if (!this._mainSoundTrack) {
  24954. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24955. }
  24956. return this._mainSoundTrack;
  24957. },
  24958. enumerable: true,
  24959. configurable: true
  24960. });
  24961. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24962. /** @hidden */
  24963. get: function () {
  24964. return this._alternateRendering;
  24965. },
  24966. enumerable: true,
  24967. configurable: true
  24968. });
  24969. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24970. /**
  24971. * Gets the list of frustum planes (built from the active camera)
  24972. */
  24973. get: function () {
  24974. return this._frustumPlanes;
  24975. },
  24976. enumerable: true,
  24977. configurable: true
  24978. });
  24979. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24980. /**
  24981. * Gets the current geometry buffer associated to the scene.
  24982. */
  24983. get: function () {
  24984. return this._geometryBufferRenderer;
  24985. },
  24986. /**
  24987. * Sets the current geometry buffer for the scene.
  24988. */
  24989. set: function (geometryBufferRenderer) {
  24990. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24991. this._geometryBufferRenderer = geometryBufferRenderer;
  24992. }
  24993. },
  24994. enumerable: true,
  24995. configurable: true
  24996. });
  24997. /**
  24998. * Registers the transient components if needed.
  24999. */
  25000. Scene.prototype._registerTransientComponents = function () {
  25001. // Register components that have been associated lately to the scene.
  25002. if (this._transientComponents.length > 0) {
  25003. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25004. var component = _a[_i];
  25005. component.register();
  25006. }
  25007. this._transientComponents = [];
  25008. }
  25009. };
  25010. /**
  25011. * Add a component to the scene.
  25012. * Note that the ccomponent could be registered on th next frame if this is called after
  25013. * the register component stage.
  25014. * @param component Defines the component to add to the scene
  25015. */
  25016. Scene.prototype._addComponent = function (component) {
  25017. this._components.push(component);
  25018. this._transientComponents.push(component);
  25019. };
  25020. /**
  25021. * Gets a component from the scene.
  25022. * @param name defines the name of the component to retrieve
  25023. * @returns the component or null if not present
  25024. */
  25025. Scene.prototype._getComponent = function (name) {
  25026. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  25027. var component = _a[_i];
  25028. if (component.name === name) {
  25029. return component;
  25030. }
  25031. }
  25032. return null;
  25033. };
  25034. Object.defineProperty(Scene.prototype, "debugLayer", {
  25035. /**
  25036. * Gets the debug layer (aka Inspector) associated with the scene
  25037. * @see http://doc.babylonjs.com/features/playground_debuglayer
  25038. */
  25039. get: function () {
  25040. if (!this._debugLayer) {
  25041. this._debugLayer = new BABYLON.DebugLayer(this);
  25042. }
  25043. return this._debugLayer;
  25044. },
  25045. enumerable: true,
  25046. configurable: true
  25047. });
  25048. Object.defineProperty(Scene.prototype, "workerCollisions", {
  25049. /**
  25050. * Gets a boolean indicating if collisions are processed on a web worker
  25051. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  25052. */
  25053. get: function () {
  25054. return this._workerCollisions;
  25055. },
  25056. set: function (enabled) {
  25057. if (!BABYLON.CollisionCoordinatorLegacy) {
  25058. return;
  25059. }
  25060. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  25061. this._workerCollisions = enabled;
  25062. if (this.collisionCoordinator) {
  25063. this.collisionCoordinator.destroy();
  25064. }
  25065. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  25066. this.collisionCoordinator.init(this);
  25067. },
  25068. enumerable: true,
  25069. configurable: true
  25070. });
  25071. Object.defineProperty(Scene.prototype, "selectionOctree", {
  25072. /**
  25073. * Gets the octree used to boost mesh selection (picking)
  25074. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  25075. */
  25076. get: function () {
  25077. return this._selectionOctree;
  25078. },
  25079. enumerable: true,
  25080. configurable: true
  25081. });
  25082. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25083. /**
  25084. * Gets the mesh that is currently under the pointer
  25085. */
  25086. get: function () {
  25087. return this._pointerOverMesh;
  25088. },
  25089. enumerable: true,
  25090. configurable: true
  25091. });
  25092. Object.defineProperty(Scene.prototype, "pointerX", {
  25093. /**
  25094. * Gets the current on-screen X position of the pointer
  25095. */
  25096. get: function () {
  25097. return this._pointerX;
  25098. },
  25099. enumerable: true,
  25100. configurable: true
  25101. });
  25102. Object.defineProperty(Scene.prototype, "pointerY", {
  25103. /**
  25104. * Gets the current on-screen Y position of the pointer
  25105. */
  25106. get: function () {
  25107. return this._pointerY;
  25108. },
  25109. enumerable: true,
  25110. configurable: true
  25111. });
  25112. /**
  25113. * Gets the cached material (ie. the latest rendered one)
  25114. * @returns the cached material
  25115. */
  25116. Scene.prototype.getCachedMaterial = function () {
  25117. return this._cachedMaterial;
  25118. };
  25119. /**
  25120. * Gets the cached effect (ie. the latest rendered one)
  25121. * @returns the cached effect
  25122. */
  25123. Scene.prototype.getCachedEffect = function () {
  25124. return this._cachedEffect;
  25125. };
  25126. /**
  25127. * Gets the cached visibility state (ie. the latest rendered one)
  25128. * @returns the cached visibility state
  25129. */
  25130. Scene.prototype.getCachedVisibility = function () {
  25131. return this._cachedVisibility;
  25132. };
  25133. /**
  25134. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25135. * @param material defines the current material
  25136. * @param effect defines the current effect
  25137. * @param visibility defines the current visibility state
  25138. * @returns true if one parameter is not cached
  25139. */
  25140. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25141. if (visibility === void 0) { visibility = 1; }
  25142. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25143. };
  25144. /**
  25145. * Gets the bounding box renderer associated with the scene
  25146. * @returns a BoundingBoxRenderer
  25147. */
  25148. Scene.prototype.getBoundingBoxRenderer = function () {
  25149. if (!this._boundingBoxRenderer) {
  25150. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  25151. }
  25152. return this._boundingBoxRenderer;
  25153. };
  25154. /**
  25155. * Gets the outline renderer associated with the scene
  25156. * @returns a OutlineRenderer
  25157. */
  25158. Scene.prototype.getOutlineRenderer = function () {
  25159. return this._outlineRenderer;
  25160. };
  25161. /**
  25162. * Gets the engine associated with the scene
  25163. * @returns an Engine
  25164. */
  25165. Scene.prototype.getEngine = function () {
  25166. return this._engine;
  25167. };
  25168. /**
  25169. * Gets the total number of vertices rendered per frame
  25170. * @returns the total number of vertices rendered per frame
  25171. */
  25172. Scene.prototype.getTotalVertices = function () {
  25173. return this._totalVertices.current;
  25174. };
  25175. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25176. /**
  25177. * Gets the performance counter for total vertices
  25178. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25179. */
  25180. get: function () {
  25181. return this._totalVertices;
  25182. },
  25183. enumerable: true,
  25184. configurable: true
  25185. });
  25186. /**
  25187. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25188. * @returns the total number of active indices rendered per frame
  25189. */
  25190. Scene.prototype.getActiveIndices = function () {
  25191. return this._activeIndices.current;
  25192. };
  25193. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25194. /**
  25195. * Gets the performance counter for active indices
  25196. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25197. */
  25198. get: function () {
  25199. return this._activeIndices;
  25200. },
  25201. enumerable: true,
  25202. configurable: true
  25203. });
  25204. /**
  25205. * Gets the total number of active particles rendered per frame
  25206. * @returns the total number of active particles rendered per frame
  25207. */
  25208. Scene.prototype.getActiveParticles = function () {
  25209. return this._activeParticles.current;
  25210. };
  25211. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25212. /**
  25213. * Gets the performance counter for active particles
  25214. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25215. */
  25216. get: function () {
  25217. return this._activeParticles;
  25218. },
  25219. enumerable: true,
  25220. configurable: true
  25221. });
  25222. /**
  25223. * Gets the total number of active bones rendered per frame
  25224. * @returns the total number of active bones rendered per frame
  25225. */
  25226. Scene.prototype.getActiveBones = function () {
  25227. return this._activeBones.current;
  25228. };
  25229. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25230. /**
  25231. * Gets the performance counter for active bones
  25232. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25233. */
  25234. get: function () {
  25235. return this._activeBones;
  25236. },
  25237. enumerable: true,
  25238. configurable: true
  25239. });
  25240. /** @hidden */
  25241. Scene.prototype.getInterFramePerfCounter = function () {
  25242. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25243. return 0;
  25244. };
  25245. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25246. /** @hidden */
  25247. get: function () {
  25248. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25249. return null;
  25250. },
  25251. enumerable: true,
  25252. configurable: true
  25253. });
  25254. /** @hidden */
  25255. Scene.prototype.getLastFrameDuration = function () {
  25256. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25257. return 0;
  25258. };
  25259. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25260. /** @hidden */
  25261. get: function () {
  25262. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25263. return null;
  25264. },
  25265. enumerable: true,
  25266. configurable: true
  25267. });
  25268. /** @hidden */
  25269. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25270. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25271. return 0;
  25272. };
  25273. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25274. /** @hidden */
  25275. get: function () {
  25276. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25277. return null;
  25278. },
  25279. enumerable: true,
  25280. configurable: true
  25281. });
  25282. /**
  25283. * Gets the array of active meshes
  25284. * @returns an array of AbstractMesh
  25285. */
  25286. Scene.prototype.getActiveMeshes = function () {
  25287. return this._activeMeshes;
  25288. };
  25289. /** @hidden */
  25290. Scene.prototype.getRenderTargetsDuration = function () {
  25291. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25292. return 0;
  25293. };
  25294. /** @hidden */
  25295. Scene.prototype.getRenderDuration = function () {
  25296. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25297. return 0;
  25298. };
  25299. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25300. /** @hidden */
  25301. get: function () {
  25302. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25303. return null;
  25304. },
  25305. enumerable: true,
  25306. configurable: true
  25307. });
  25308. /** @hidden */
  25309. Scene.prototype.getParticlesDuration = function () {
  25310. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25311. return 0;
  25312. };
  25313. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25314. /** @hidden */
  25315. get: function () {
  25316. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25317. return null;
  25318. },
  25319. enumerable: true,
  25320. configurable: true
  25321. });
  25322. /** @hidden */
  25323. Scene.prototype.getSpritesDuration = function () {
  25324. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25325. return 0;
  25326. };
  25327. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25328. /** @hidden */
  25329. get: function () {
  25330. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25331. return null;
  25332. },
  25333. enumerable: true,
  25334. configurable: true
  25335. });
  25336. /**
  25337. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25338. * @returns a number
  25339. */
  25340. Scene.prototype.getAnimationRatio = function () {
  25341. return this._animationRatio;
  25342. };
  25343. /**
  25344. * Gets an unique Id for the current frame
  25345. * @returns a number
  25346. */
  25347. Scene.prototype.getRenderId = function () {
  25348. return this._renderId;
  25349. };
  25350. /** Call this function if you want to manually increment the render Id*/
  25351. Scene.prototype.incrementRenderId = function () {
  25352. this._renderId++;
  25353. };
  25354. Scene.prototype._updatePointerPosition = function (evt) {
  25355. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25356. if (!canvasRect) {
  25357. return;
  25358. }
  25359. this._pointerX = evt.clientX - canvasRect.left;
  25360. this._pointerY = evt.clientY - canvasRect.top;
  25361. this._unTranslatedPointerX = this._pointerX;
  25362. this._unTranslatedPointerY = this._pointerY;
  25363. };
  25364. Scene.prototype._createUbo = function () {
  25365. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25366. this._sceneUbo.addUniform("viewProjection", 16);
  25367. this._sceneUbo.addUniform("view", 16);
  25368. };
  25369. Scene.prototype._createAlternateUbo = function () {
  25370. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25371. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25372. this._alternateSceneUbo.addUniform("view", 16);
  25373. };
  25374. // Pointers handling
  25375. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25376. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25377. if (result) {
  25378. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25379. }
  25380. return result;
  25381. };
  25382. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25383. if (pointerInfo.pickInfo) {
  25384. if (!pointerInfo.pickInfo.ray) {
  25385. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25386. }
  25387. }
  25388. };
  25389. /**
  25390. * Use this method to simulate a pointer move on a mesh
  25391. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25392. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25393. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25394. * @returns the current scene
  25395. */
  25396. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25397. var evt = new PointerEvent("pointermove", pointerEventInit);
  25398. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25399. return this;
  25400. }
  25401. return this._processPointerMove(pickResult, evt);
  25402. };
  25403. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25404. var canvas = this._engine.getRenderingCanvas();
  25405. if (!canvas) {
  25406. return this;
  25407. }
  25408. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25409. this.setPointerOverSprite(null);
  25410. this.setPointerOverMesh(pickResult.pickedMesh);
  25411. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25412. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25413. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25414. }
  25415. else {
  25416. canvas.style.cursor = this.hoverCursor;
  25417. }
  25418. }
  25419. else {
  25420. canvas.style.cursor = this.defaultCursor;
  25421. }
  25422. }
  25423. else {
  25424. this.setPointerOverMesh(null);
  25425. // Sprites
  25426. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25427. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25428. this.setPointerOverSprite(pickResult.pickedSprite);
  25429. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25430. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25431. }
  25432. else {
  25433. canvas.style.cursor = this.hoverCursor;
  25434. }
  25435. }
  25436. else {
  25437. this.setPointerOverSprite(null);
  25438. // Restore pointer
  25439. canvas.style.cursor = this.defaultCursor;
  25440. }
  25441. }
  25442. if (pickResult) {
  25443. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25444. if (this.onPointerMove) {
  25445. this.onPointerMove(evt, pickResult, type);
  25446. }
  25447. if (this.onPointerObservable.hasObservers()) {
  25448. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25449. this._setRayOnPointerInfo(pi);
  25450. this.onPointerObservable.notifyObservers(pi, type);
  25451. }
  25452. }
  25453. return this;
  25454. };
  25455. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25456. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25457. if (pickResult) {
  25458. pi.ray = pickResult.ray;
  25459. }
  25460. this.onPrePointerObservable.notifyObservers(pi, type);
  25461. if (pi.skipOnPointerObservable) {
  25462. return true;
  25463. }
  25464. else {
  25465. return false;
  25466. }
  25467. };
  25468. /**
  25469. * Use this method to simulate a pointer down on a mesh
  25470. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25471. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25472. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25473. * @returns the current scene
  25474. */
  25475. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25476. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25477. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25478. return this;
  25479. }
  25480. return this._processPointerDown(pickResult, evt);
  25481. };
  25482. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25483. var _this = this;
  25484. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25485. this._pickedDownMesh = pickResult.pickedMesh;
  25486. var actionManager = pickResult.pickedMesh.actionManager;
  25487. if (actionManager) {
  25488. if (actionManager.hasPickTriggers) {
  25489. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25490. switch (evt.button) {
  25491. case 0:
  25492. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25493. break;
  25494. case 1:
  25495. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25496. break;
  25497. case 2:
  25498. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25499. break;
  25500. }
  25501. }
  25502. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25503. window.setTimeout(function () {
  25504. 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);
  25505. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25506. if (_this._totalPointersPressed !== 0 &&
  25507. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25508. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25509. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25510. _this._startingPointerTime = 0;
  25511. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25512. }
  25513. }
  25514. }, Scene.LongPressDelay);
  25515. }
  25516. }
  25517. }
  25518. if (pickResult) {
  25519. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25520. if (this.onPointerDown) {
  25521. this.onPointerDown(evt, pickResult, type);
  25522. }
  25523. if (this.onPointerObservable.hasObservers()) {
  25524. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25525. this._setRayOnPointerInfo(pi);
  25526. this.onPointerObservable.notifyObservers(pi, type);
  25527. }
  25528. }
  25529. return this;
  25530. };
  25531. /**
  25532. * Use this method to simulate a pointer up on a mesh
  25533. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25534. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25535. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25536. * @returns the current scene
  25537. */
  25538. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25539. var evt = new PointerEvent("pointerup", pointerEventInit);
  25540. var clickInfo = new ClickInfo();
  25541. clickInfo.singleClick = true;
  25542. clickInfo.ignore = true;
  25543. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25544. return this;
  25545. }
  25546. return this._processPointerUp(pickResult, evt, clickInfo);
  25547. };
  25548. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25549. if (pickResult && pickResult && pickResult.pickedMesh) {
  25550. this._pickedUpMesh = pickResult.pickedMesh;
  25551. if (this._pickedDownMesh === this._pickedUpMesh) {
  25552. if (this.onPointerPick) {
  25553. this.onPointerPick(evt, pickResult);
  25554. }
  25555. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25556. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25557. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25558. this._setRayOnPointerInfo(pi);
  25559. this.onPointerObservable.notifyObservers(pi, type_1);
  25560. }
  25561. }
  25562. if (pickResult.pickedMesh.actionManager) {
  25563. if (clickInfo.ignore) {
  25564. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25565. }
  25566. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25567. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25568. }
  25569. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25570. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25571. }
  25572. }
  25573. }
  25574. if (this._pickedDownMesh &&
  25575. this._pickedDownMesh.actionManager &&
  25576. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25577. this._pickedDownMesh !== this._pickedUpMesh) {
  25578. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25579. }
  25580. var type = BABYLON.PointerEventTypes.POINTERUP;
  25581. if (this.onPointerObservable.hasObservers()) {
  25582. if (!clickInfo.ignore) {
  25583. if (!clickInfo.hasSwiped) {
  25584. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25585. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25586. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25587. this._setRayOnPointerInfo(pi);
  25588. this.onPointerObservable.notifyObservers(pi, type_2);
  25589. }
  25590. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25591. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25592. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25593. this._setRayOnPointerInfo(pi);
  25594. this.onPointerObservable.notifyObservers(pi, type_3);
  25595. }
  25596. }
  25597. }
  25598. else {
  25599. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25600. this._setRayOnPointerInfo(pi);
  25601. this.onPointerObservable.notifyObservers(pi, type);
  25602. }
  25603. }
  25604. if (this.onPointerUp) {
  25605. this.onPointerUp(evt, pickResult, type);
  25606. }
  25607. return this;
  25608. };
  25609. /**
  25610. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25611. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25612. * @returns true if the pointer was captured
  25613. */
  25614. Scene.prototype.isPointerCaptured = function (pointerId) {
  25615. if (pointerId === void 0) { pointerId = 0; }
  25616. return this._pointerCaptures[pointerId];
  25617. };
  25618. /**
  25619. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25620. * @param attachUp defines if you want to attach events to pointerup
  25621. * @param attachDown defines if you want to attach events to pointerdown
  25622. * @param attachMove defines if you want to attach events to pointermove
  25623. */
  25624. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25625. var _this = this;
  25626. if (attachUp === void 0) { attachUp = true; }
  25627. if (attachDown === void 0) { attachDown = true; }
  25628. if (attachMove === void 0) { attachMove = true; }
  25629. this._initActionManager = function (act, clickInfo) {
  25630. if (!_this._meshPickProceed) {
  25631. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25632. _this._currentPickResult = pickResult;
  25633. if (pickResult) {
  25634. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25635. }
  25636. _this._meshPickProceed = true;
  25637. }
  25638. return act;
  25639. };
  25640. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25641. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25642. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25643. btn !== _this._previousButtonPressed) {
  25644. _this._doubleClickOccured = false;
  25645. clickInfo.singleClick = true;
  25646. clickInfo.ignore = false;
  25647. cb(clickInfo, _this._currentPickResult);
  25648. }
  25649. };
  25650. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25651. var clickInfo = new ClickInfo();
  25652. _this._currentPickResult = null;
  25653. var act = null;
  25654. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25655. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25656. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25657. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25658. act = _this._initActionManager(act, clickInfo);
  25659. if (act)
  25660. checkPicking = act.hasPickTriggers;
  25661. }
  25662. if (checkPicking) {
  25663. var btn = evt.button;
  25664. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25665. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25666. if (!clickInfo.hasSwiped) {
  25667. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25668. if (!checkSingleClickImmediately) {
  25669. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25670. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25671. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25672. act = _this._initActionManager(act, clickInfo);
  25673. if (act)
  25674. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25675. }
  25676. }
  25677. if (checkSingleClickImmediately) {
  25678. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25679. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25680. btn !== _this._previousButtonPressed) {
  25681. clickInfo.singleClick = true;
  25682. cb(clickInfo, _this._currentPickResult);
  25683. }
  25684. }
  25685. // at least one double click is required to be check and exclusive double click is enabled
  25686. else {
  25687. // wait that no double click has been raised during the double click delay
  25688. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25689. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25690. }
  25691. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25692. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25693. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25694. act = _this._initActionManager(act, clickInfo);
  25695. if (act)
  25696. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25697. }
  25698. if (checkDoubleClick) {
  25699. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25700. if (btn === _this._previousButtonPressed &&
  25701. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25702. !_this._doubleClickOccured) {
  25703. // pointer has not moved for 2 clicks, it's a double click
  25704. if (!clickInfo.hasSwiped &&
  25705. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25706. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25707. _this._previousStartingPointerTime = 0;
  25708. _this._doubleClickOccured = true;
  25709. clickInfo.doubleClick = true;
  25710. clickInfo.ignore = false;
  25711. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25712. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25713. }
  25714. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25715. cb(clickInfo, _this._currentPickResult);
  25716. }
  25717. // if the two successive clicks are too far, it's just two simple clicks
  25718. else {
  25719. _this._doubleClickOccured = false;
  25720. _this._previousStartingPointerTime = _this._startingPointerTime;
  25721. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25722. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25723. _this._previousButtonPressed = btn;
  25724. if (Scene.ExclusiveDoubleClickMode) {
  25725. if (_this._previousDelayedSimpleClickTimeout) {
  25726. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25727. }
  25728. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25729. cb(clickInfo, _this._previousPickResult);
  25730. }
  25731. else {
  25732. cb(clickInfo, _this._currentPickResult);
  25733. }
  25734. }
  25735. }
  25736. // just the first click of the double has been raised
  25737. else {
  25738. _this._doubleClickOccured = false;
  25739. _this._previousStartingPointerTime = _this._startingPointerTime;
  25740. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25741. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25742. _this._previousButtonPressed = btn;
  25743. }
  25744. }
  25745. }
  25746. }
  25747. clickInfo.ignore = true;
  25748. cb(clickInfo, _this._currentPickResult);
  25749. };
  25750. this._spritePredicate = function (sprite) {
  25751. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25752. };
  25753. this._onPointerMove = function (evt) {
  25754. _this._updatePointerPosition(evt);
  25755. // PreObservable support
  25756. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25757. return;
  25758. }
  25759. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25760. return;
  25761. }
  25762. if (!_this.pointerMovePredicate) {
  25763. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25764. }
  25765. // Meshes
  25766. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25767. _this._processPointerMove(pickResult, evt);
  25768. };
  25769. this._onPointerDown = function (evt) {
  25770. _this._totalPointersPressed++;
  25771. _this._pickedDownMesh = null;
  25772. _this._meshPickProceed = false;
  25773. _this._updatePointerPosition(evt);
  25774. if (_this.preventDefaultOnPointerDown && canvas) {
  25775. evt.preventDefault();
  25776. canvas.focus();
  25777. }
  25778. // PreObservable support
  25779. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25780. return;
  25781. }
  25782. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25783. return;
  25784. }
  25785. _this._pointerCaptures[evt.pointerId] = true;
  25786. _this._startingPointerPosition.x = _this._pointerX;
  25787. _this._startingPointerPosition.y = _this._pointerY;
  25788. _this._startingPointerTime = Date.now();
  25789. if (!_this.pointerDownPredicate) {
  25790. _this.pointerDownPredicate = function (mesh) {
  25791. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25792. };
  25793. }
  25794. // Meshes
  25795. _this._pickedDownMesh = null;
  25796. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25797. _this._processPointerDown(pickResult, evt);
  25798. // Sprites
  25799. _this._pickedDownSprite = null;
  25800. if (_this.spriteManagers.length > 0) {
  25801. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25802. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25803. if (pickResult.pickedSprite.actionManager) {
  25804. _this._pickedDownSprite = pickResult.pickedSprite;
  25805. switch (evt.button) {
  25806. case 0:
  25807. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25808. break;
  25809. case 1:
  25810. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25811. break;
  25812. case 2:
  25813. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25814. break;
  25815. }
  25816. if (pickResult.pickedSprite.actionManager) {
  25817. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25818. }
  25819. }
  25820. }
  25821. }
  25822. };
  25823. this._onPointerUp = function (evt) {
  25824. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25825. return; // So we need to test it the pointer down was pressed before.
  25826. }
  25827. _this._totalPointersPressed--;
  25828. _this._pickedUpMesh = null;
  25829. _this._meshPickProceed = false;
  25830. _this._updatePointerPosition(evt);
  25831. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25832. // PreObservable support
  25833. if (_this.onPrePointerObservable.hasObservers()) {
  25834. if (!clickInfo.ignore) {
  25835. if (!clickInfo.hasSwiped) {
  25836. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25837. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25838. return;
  25839. }
  25840. }
  25841. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25842. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25843. return;
  25844. }
  25845. }
  25846. }
  25847. }
  25848. else {
  25849. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25850. return;
  25851. }
  25852. }
  25853. }
  25854. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25855. return;
  25856. }
  25857. _this._pointerCaptures[evt.pointerId] = false;
  25858. if (!_this.pointerUpPredicate) {
  25859. _this.pointerUpPredicate = function (mesh) {
  25860. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25861. };
  25862. }
  25863. // Meshes
  25864. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25865. _this._initActionManager(null, clickInfo);
  25866. }
  25867. if (!pickResult) {
  25868. pickResult = _this._currentPickResult;
  25869. }
  25870. _this._processPointerUp(pickResult, evt, clickInfo);
  25871. // Sprites
  25872. if (!clickInfo.ignore) {
  25873. if (_this.spriteManagers.length > 0) {
  25874. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25875. if (spritePickResult) {
  25876. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25877. if (spritePickResult.pickedSprite.actionManager) {
  25878. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25879. if (spritePickResult.pickedSprite.actionManager) {
  25880. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25881. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25882. }
  25883. }
  25884. }
  25885. }
  25886. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25887. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25888. }
  25889. }
  25890. }
  25891. }
  25892. _this._previousPickResult = _this._currentPickResult;
  25893. });
  25894. };
  25895. this._onKeyDown = function (evt) {
  25896. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25897. if (_this.onPreKeyboardObservable.hasObservers()) {
  25898. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25899. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25900. if (pi.skipOnPointerObservable) {
  25901. return;
  25902. }
  25903. }
  25904. if (_this.onKeyboardObservable.hasObservers()) {
  25905. var pi = new BABYLON.KeyboardInfo(type, evt);
  25906. _this.onKeyboardObservable.notifyObservers(pi, type);
  25907. }
  25908. if (_this.actionManager) {
  25909. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25910. }
  25911. };
  25912. this._onKeyUp = function (evt) {
  25913. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25914. if (_this.onPreKeyboardObservable.hasObservers()) {
  25915. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25916. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25917. if (pi.skipOnPointerObservable) {
  25918. return;
  25919. }
  25920. }
  25921. if (_this.onKeyboardObservable.hasObservers()) {
  25922. var pi = new BABYLON.KeyboardInfo(type, evt);
  25923. _this.onKeyboardObservable.notifyObservers(pi, type);
  25924. }
  25925. if (_this.actionManager) {
  25926. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25927. }
  25928. };
  25929. var engine = this.getEngine();
  25930. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25931. if (!canvas) {
  25932. return;
  25933. }
  25934. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25935. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25936. });
  25937. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25938. if (!canvas) {
  25939. return;
  25940. }
  25941. canvas.removeEventListener("keydown", _this._onKeyDown);
  25942. canvas.removeEventListener("keyup", _this._onKeyUp);
  25943. });
  25944. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25945. var canvas = this._engine.getRenderingCanvas();
  25946. if (!canvas) {
  25947. return;
  25948. }
  25949. if (attachMove) {
  25950. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25951. // Wheel
  25952. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25953. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25954. }
  25955. if (attachDown) {
  25956. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25957. }
  25958. if (attachUp) {
  25959. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25960. }
  25961. canvas.tabIndex = 1;
  25962. };
  25963. /** Detaches all event handlers*/
  25964. Scene.prototype.detachControl = function () {
  25965. var engine = this.getEngine();
  25966. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25967. var canvas = engine.getRenderingCanvas();
  25968. if (!canvas) {
  25969. return;
  25970. }
  25971. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25972. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25973. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25974. if (this._onCanvasBlurObserver) {
  25975. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25976. }
  25977. if (this._onCanvasFocusObserver) {
  25978. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25979. }
  25980. // Wheel
  25981. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25982. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25983. // Keyboard
  25984. canvas.removeEventListener("keydown", this._onKeyDown);
  25985. canvas.removeEventListener("keyup", this._onKeyUp);
  25986. // Observables
  25987. this.onKeyboardObservable.clear();
  25988. this.onPreKeyboardObservable.clear();
  25989. this.onPointerObservable.clear();
  25990. this.onPrePointerObservable.clear();
  25991. };
  25992. /**
  25993. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25994. * Delay loaded resources are not taking in account
  25995. * @return true if all required resources are ready
  25996. */
  25997. Scene.prototype.isReady = function () {
  25998. if (this._isDisposed) {
  25999. return false;
  26000. }
  26001. if (this._pendingData.length > 0) {
  26002. return false;
  26003. }
  26004. var index;
  26005. var engine = this.getEngine();
  26006. // Geometries
  26007. for (index = 0; index < this.geometries.length; index++) {
  26008. var geometry = this.geometries[index];
  26009. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26010. return false;
  26011. }
  26012. }
  26013. // Meshes
  26014. for (index = 0; index < this.meshes.length; index++) {
  26015. var mesh = this.meshes[index];
  26016. if (!mesh.isEnabled()) {
  26017. continue;
  26018. }
  26019. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26020. continue;
  26021. }
  26022. if (!mesh.isReady(true)) {
  26023. return false;
  26024. }
  26025. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26026. // Is Ready For Mesh
  26027. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26028. var step = _a[_i];
  26029. if (!step.action(mesh, hardwareInstancedRendering)) {
  26030. return false;
  26031. }
  26032. }
  26033. }
  26034. // Post-processes
  26035. if (this.activeCameras && this.activeCameras.length > 0) {
  26036. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26037. var camera = _c[_b];
  26038. if (!camera.isReady(true)) {
  26039. return false;
  26040. }
  26041. }
  26042. }
  26043. else if (this.activeCamera) {
  26044. if (!this.activeCamera.isReady(true)) {
  26045. return false;
  26046. }
  26047. }
  26048. // Particles
  26049. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26050. var particleSystem = _e[_d];
  26051. if (!particleSystem.isReady()) {
  26052. return false;
  26053. }
  26054. }
  26055. return true;
  26056. };
  26057. /** Resets all cached information relative to material (including effect and visibility) */
  26058. Scene.prototype.resetCachedMaterial = function () {
  26059. this._cachedMaterial = null;
  26060. this._cachedEffect = null;
  26061. this._cachedVisibility = null;
  26062. };
  26063. /**
  26064. * Registers a function to be called before every frame render
  26065. * @param func defines the function to register
  26066. */
  26067. Scene.prototype.registerBeforeRender = function (func) {
  26068. this.onBeforeRenderObservable.add(func);
  26069. };
  26070. /**
  26071. * Unregisters a function called before every frame render
  26072. * @param func defines the function to unregister
  26073. */
  26074. Scene.prototype.unregisterBeforeRender = function (func) {
  26075. this.onBeforeRenderObservable.removeCallback(func);
  26076. };
  26077. /**
  26078. * Registers a function to be called after every frame render
  26079. * @param func defines the function to register
  26080. */
  26081. Scene.prototype.registerAfterRender = function (func) {
  26082. this.onAfterRenderObservable.add(func);
  26083. };
  26084. /**
  26085. * Unregisters a function called after every frame render
  26086. * @param func defines the function to unregister
  26087. */
  26088. Scene.prototype.unregisterAfterRender = function (func) {
  26089. this.onAfterRenderObservable.removeCallback(func);
  26090. };
  26091. Scene.prototype._executeOnceBeforeRender = function (func) {
  26092. var _this = this;
  26093. var execFunc = function () {
  26094. func();
  26095. setTimeout(function () {
  26096. _this.unregisterBeforeRender(execFunc);
  26097. });
  26098. };
  26099. this.registerBeforeRender(execFunc);
  26100. };
  26101. /**
  26102. * The provided function will run before render once and will be disposed afterwards.
  26103. * A timeout delay can be provided so that the function will be executed in N ms.
  26104. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26105. * @param func The function to be executed.
  26106. * @param timeout optional delay in ms
  26107. */
  26108. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26109. var _this = this;
  26110. if (timeout !== undefined) {
  26111. setTimeout(function () {
  26112. _this._executeOnceBeforeRender(func);
  26113. }, timeout);
  26114. }
  26115. else {
  26116. this._executeOnceBeforeRender(func);
  26117. }
  26118. };
  26119. /** @hidden */
  26120. Scene.prototype._addPendingData = function (data) {
  26121. this._pendingData.push(data);
  26122. };
  26123. /** @hidden */
  26124. Scene.prototype._removePendingData = function (data) {
  26125. var wasLoading = this.isLoading;
  26126. var index = this._pendingData.indexOf(data);
  26127. if (index !== -1) {
  26128. this._pendingData.splice(index, 1);
  26129. }
  26130. if (wasLoading && !this.isLoading) {
  26131. this.onDataLoadedObservable.notifyObservers(this);
  26132. }
  26133. };
  26134. /**
  26135. * Returns the number of items waiting to be loaded
  26136. * @returns the number of items waiting to be loaded
  26137. */
  26138. Scene.prototype.getWaitingItemsCount = function () {
  26139. return this._pendingData.length;
  26140. };
  26141. Object.defineProperty(Scene.prototype, "isLoading", {
  26142. /**
  26143. * Returns a boolean indicating if the scene is still loading data
  26144. */
  26145. get: function () {
  26146. return this._pendingData.length > 0;
  26147. },
  26148. enumerable: true,
  26149. configurable: true
  26150. });
  26151. /**
  26152. * Registers a function to be executed when the scene is ready
  26153. * @param {Function} func - the function to be executed
  26154. */
  26155. Scene.prototype.executeWhenReady = function (func) {
  26156. var _this = this;
  26157. this.onReadyObservable.add(func);
  26158. if (this._executeWhenReadyTimeoutId !== -1) {
  26159. return;
  26160. }
  26161. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26162. _this._checkIsReady();
  26163. }, 150);
  26164. };
  26165. /**
  26166. * Returns a promise that resolves when the scene is ready
  26167. * @returns A promise that resolves when the scene is ready
  26168. */
  26169. Scene.prototype.whenReadyAsync = function () {
  26170. var _this = this;
  26171. return new Promise(function (resolve) {
  26172. _this.executeWhenReady(function () {
  26173. resolve();
  26174. });
  26175. });
  26176. };
  26177. /** @hidden */
  26178. Scene.prototype._checkIsReady = function () {
  26179. var _this = this;
  26180. this._registerTransientComponents();
  26181. if (this.isReady()) {
  26182. this.onReadyObservable.notifyObservers(this);
  26183. this.onReadyObservable.clear();
  26184. this._executeWhenReadyTimeoutId = -1;
  26185. return;
  26186. }
  26187. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26188. _this._checkIsReady();
  26189. }, 150);
  26190. };
  26191. // Animations
  26192. /**
  26193. * Will start the animation sequence of a given target
  26194. * @param target defines the target
  26195. * @param from defines from which frame should animation start
  26196. * @param to defines until which frame should animation run.
  26197. * @param weight defines the weight to apply to the animation (1.0 by default)
  26198. * @param loop defines if the animation loops
  26199. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26200. * @param onAnimationEnd defines the function to be executed when the animation ends
  26201. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26202. * @returns the animatable object created for this animation
  26203. */
  26204. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  26205. if (weight === void 0) { weight = 1.0; }
  26206. if (speedRatio === void 0) { speedRatio = 1.0; }
  26207. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  26208. returnedAnimatable.weight = weight;
  26209. return returnedAnimatable;
  26210. };
  26211. /**
  26212. * Will start the animation sequence of a given target
  26213. * @param target defines the target
  26214. * @param from defines from which frame should animation start
  26215. * @param to defines until which frame should animation run.
  26216. * @param loop defines if the animation loops
  26217. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26218. * @param onAnimationEnd defines the function to be executed when the animation ends
  26219. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26220. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26221. * @returns the animatable object created for this animation
  26222. */
  26223. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26224. if (speedRatio === void 0) { speedRatio = 1.0; }
  26225. if (stopCurrent === void 0) { stopCurrent = true; }
  26226. if (from > to && speedRatio > 0) {
  26227. speedRatio *= -1;
  26228. }
  26229. if (stopCurrent) {
  26230. this.stopAnimation(target);
  26231. }
  26232. if (!animatable) {
  26233. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26234. }
  26235. // Local animations
  26236. if (target.animations) {
  26237. animatable.appendAnimations(target, target.animations);
  26238. }
  26239. // Children animations
  26240. if (target.getAnimatables) {
  26241. var animatables = target.getAnimatables();
  26242. for (var index = 0; index < animatables.length; index++) {
  26243. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26244. }
  26245. }
  26246. animatable.reset();
  26247. return animatable;
  26248. };
  26249. /**
  26250. * Begin a new animation on a given node
  26251. * @param target defines the target where the animation will take place
  26252. * @param animations defines the list of animations to start
  26253. * @param from defines the initial value
  26254. * @param to defines the final value
  26255. * @param loop defines if you want animation to loop (off by default)
  26256. * @param speedRatio defines the speed ratio to apply to all animations
  26257. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26258. * @returns the list of created animatables
  26259. */
  26260. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26261. if (speedRatio === undefined) {
  26262. speedRatio = 1.0;
  26263. }
  26264. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26265. return animatable;
  26266. };
  26267. /**
  26268. * Begin a new animation on a given node and its hierarchy
  26269. * @param target defines the root node where the animation will take place
  26270. * @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.
  26271. * @param animations defines the list of animations to start
  26272. * @param from defines the initial value
  26273. * @param to defines the final value
  26274. * @param loop defines if you want animation to loop (off by default)
  26275. * @param speedRatio defines the speed ratio to apply to all animations
  26276. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26277. * @returns the list of animatables created for all nodes
  26278. */
  26279. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26280. var children = target.getDescendants(directDescendantsOnly);
  26281. var result = [];
  26282. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26283. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26284. var child = children_1[_i];
  26285. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26286. }
  26287. return result;
  26288. };
  26289. /**
  26290. * Gets the animatable associated with a specific target
  26291. * @param target defines the target of the animatable
  26292. * @returns the required animatable if found
  26293. */
  26294. Scene.prototype.getAnimatableByTarget = function (target) {
  26295. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26296. if (this._activeAnimatables[index].target === target) {
  26297. return this._activeAnimatables[index];
  26298. }
  26299. }
  26300. return null;
  26301. };
  26302. /**
  26303. * Gets all animatables associated with a given target
  26304. * @param target defines the target to look animatables for
  26305. * @returns an array of Animatables
  26306. */
  26307. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26308. var result = [];
  26309. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26310. if (this._activeAnimatables[index].target === target) {
  26311. result.push(this._activeAnimatables[index]);
  26312. }
  26313. }
  26314. return result;
  26315. };
  26316. Object.defineProperty(Scene.prototype, "animatables", {
  26317. /**
  26318. * Gets all animatable attached to the scene
  26319. */
  26320. get: function () {
  26321. return this._activeAnimatables;
  26322. },
  26323. enumerable: true,
  26324. configurable: true
  26325. });
  26326. /**
  26327. * Will stop the animation of the given target
  26328. * @param target - the target
  26329. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26330. */
  26331. Scene.prototype.stopAnimation = function (target, animationName) {
  26332. var animatables = this.getAllAnimatablesByTarget(target);
  26333. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26334. var animatable = animatables_1[_i];
  26335. animatable.stop(animationName);
  26336. }
  26337. };
  26338. /**
  26339. * Stops and removes all animations that have been applied to the scene
  26340. */
  26341. Scene.prototype.stopAllAnimations = function () {
  26342. if (this._activeAnimatables) {
  26343. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26344. this._activeAnimatables[i].stop();
  26345. }
  26346. this._activeAnimatables = [];
  26347. }
  26348. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26349. var group = _a[_i];
  26350. group.stop();
  26351. }
  26352. };
  26353. Scene.prototype._animate = function () {
  26354. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26355. return;
  26356. }
  26357. // Getting time
  26358. var now = BABYLON.Tools.Now;
  26359. if (!this._animationTimeLast) {
  26360. if (this._pendingData.length > 0) {
  26361. return;
  26362. }
  26363. this._animationTimeLast = now;
  26364. }
  26365. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26366. this._animationTime += deltaTime;
  26367. this._animationTimeLast = now;
  26368. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26369. this._activeAnimatables[index]._animate(this._animationTime);
  26370. }
  26371. // Late animation bindings
  26372. this._processLateAnimationBindings();
  26373. };
  26374. /** @hidden */
  26375. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26376. var target = runtimeAnimation.target;
  26377. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26378. if (!target._lateAnimationHolders) {
  26379. target._lateAnimationHolders = {};
  26380. }
  26381. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26382. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26383. totalWeight: 0,
  26384. animations: [],
  26385. originalValue: originalValue
  26386. };
  26387. }
  26388. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26389. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26390. };
  26391. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26392. var normalizer = 1.0;
  26393. var finalPosition = BABYLON.Tmp.Vector3[0];
  26394. var finalScaling = BABYLON.Tmp.Vector3[1];
  26395. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26396. var startIndex = 0;
  26397. var originalAnimation = holder.animations[0];
  26398. var originalValue = holder.originalValue;
  26399. var scale = 1;
  26400. if (holder.totalWeight < 1.0) {
  26401. // We need to mix the original value in
  26402. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26403. scale = 1.0 - holder.totalWeight;
  26404. }
  26405. else {
  26406. startIndex = 1;
  26407. // We need to normalize the weights
  26408. normalizer = holder.totalWeight;
  26409. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26410. scale = originalAnimation.weight / normalizer;
  26411. if (scale == 1) {
  26412. return originalAnimation.currentValue;
  26413. }
  26414. }
  26415. finalScaling.scaleInPlace(scale);
  26416. finalPosition.scaleInPlace(scale);
  26417. finalQuaternion.scaleInPlace(scale);
  26418. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26419. var runtimeAnimation = holder.animations[animIndex];
  26420. var scale = runtimeAnimation.weight / normalizer;
  26421. var currentPosition = BABYLON.Tmp.Vector3[2];
  26422. var currentScaling = BABYLON.Tmp.Vector3[3];
  26423. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26424. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26425. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26426. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26427. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26428. }
  26429. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26430. return originalAnimation._workValue;
  26431. };
  26432. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26433. var originalAnimation = holder.animations[0];
  26434. var originalValue = holder.originalValue;
  26435. if (holder.animations.length === 1) {
  26436. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26437. }
  26438. var normalizer = 1.0;
  26439. var quaternions;
  26440. var weights;
  26441. if (holder.totalWeight < 1.0) {
  26442. var scale = 1.0 - holder.totalWeight;
  26443. quaternions = [];
  26444. weights = [];
  26445. quaternions.push(originalValue);
  26446. weights.push(scale);
  26447. }
  26448. else {
  26449. if (holder.animations.length === 2) { // Slerp as soon as we can
  26450. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26451. }
  26452. quaternions = [];
  26453. weights = [];
  26454. normalizer = holder.totalWeight;
  26455. }
  26456. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26457. var runtimeAnimation = holder.animations[animIndex];
  26458. quaternions.push(runtimeAnimation.currentValue);
  26459. weights.push(runtimeAnimation.weight / normalizer);
  26460. }
  26461. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26462. var cumulativeAmount = 0;
  26463. var cumulativeQuaternion = null;
  26464. for (var index = 0; index < quaternions.length;) {
  26465. if (!cumulativeQuaternion) {
  26466. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26467. cumulativeAmount = weights[index] + weights[index + 1];
  26468. index += 2;
  26469. continue;
  26470. }
  26471. cumulativeAmount += weights[index];
  26472. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26473. index++;
  26474. }
  26475. return cumulativeQuaternion;
  26476. };
  26477. Scene.prototype._processLateAnimationBindings = function () {
  26478. if (!this._registeredForLateAnimationBindings.length) {
  26479. return;
  26480. }
  26481. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26482. var target = this._registeredForLateAnimationBindings.data[index];
  26483. for (var path in target._lateAnimationHolders) {
  26484. var holder = target._lateAnimationHolders[path];
  26485. var originalAnimation = holder.animations[0];
  26486. var originalValue = holder.originalValue;
  26487. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26488. var finalValue = void 0;
  26489. if (matrixDecomposeMode) {
  26490. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26491. }
  26492. else {
  26493. var quaternionMode = originalValue.w !== undefined;
  26494. if (quaternionMode) {
  26495. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26496. }
  26497. else {
  26498. var startIndex = 0;
  26499. var normalizer = 1.0;
  26500. if (holder.totalWeight < 1.0) {
  26501. // We need to mix the original value in
  26502. if (originalValue.scale) {
  26503. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26504. }
  26505. else {
  26506. finalValue = originalValue * (1.0 - holder.totalWeight);
  26507. }
  26508. }
  26509. else {
  26510. // We need to normalize the weights
  26511. normalizer = holder.totalWeight;
  26512. var scale_1 = originalAnimation.weight / normalizer;
  26513. if (scale_1 !== 1) {
  26514. if (originalAnimation.currentValue.scale) {
  26515. finalValue = originalAnimation.currentValue.scale(scale_1);
  26516. }
  26517. else {
  26518. finalValue = originalAnimation.currentValue * scale_1;
  26519. }
  26520. }
  26521. else {
  26522. finalValue = originalAnimation.currentValue;
  26523. }
  26524. startIndex = 1;
  26525. }
  26526. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26527. var runtimeAnimation = holder.animations[animIndex];
  26528. var scale = runtimeAnimation.weight / normalizer;
  26529. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26530. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26531. }
  26532. else {
  26533. finalValue += runtimeAnimation.currentValue * scale;
  26534. }
  26535. }
  26536. }
  26537. }
  26538. target[path] = finalValue;
  26539. }
  26540. target._lateAnimationHolders = {};
  26541. }
  26542. this._registeredForLateAnimationBindings.reset();
  26543. };
  26544. // Matrix
  26545. /** @hidden */
  26546. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26547. this._useAlternateCameraConfiguration = active;
  26548. };
  26549. /**
  26550. * Gets the current view matrix
  26551. * @returns a Matrix
  26552. */
  26553. Scene.prototype.getViewMatrix = function () {
  26554. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26555. };
  26556. /**
  26557. * Gets the current projection matrix
  26558. * @returns a Matrix
  26559. */
  26560. Scene.prototype.getProjectionMatrix = function () {
  26561. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26562. };
  26563. /**
  26564. * Gets the current transform matrix
  26565. * @returns a Matrix made of View * Projection
  26566. */
  26567. Scene.prototype.getTransformMatrix = function () {
  26568. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26569. };
  26570. /**
  26571. * Sets the current transform matrix
  26572. * @param view defines the View matrix to use
  26573. * @param projection defines the Projection matrix to use
  26574. */
  26575. Scene.prototype.setTransformMatrix = function (view, projection) {
  26576. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26577. return;
  26578. }
  26579. this._viewUpdateFlag = view.updateFlag;
  26580. this._projectionUpdateFlag = projection.updateFlag;
  26581. this._viewMatrix = view;
  26582. this._projectionMatrix = projection;
  26583. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26584. // Update frustum
  26585. if (!this._frustumPlanes) {
  26586. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26587. }
  26588. else {
  26589. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26590. }
  26591. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26592. var otherCamera = this.activeCamera._alternateCamera;
  26593. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26594. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26595. }
  26596. if (this._sceneUbo.useUbo) {
  26597. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26598. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26599. this._sceneUbo.update();
  26600. }
  26601. };
  26602. /** @hidden */
  26603. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26604. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26605. return;
  26606. }
  26607. this._alternateViewUpdateFlag = view.updateFlag;
  26608. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26609. this._alternateViewMatrix = view;
  26610. this._alternateProjectionMatrix = projection;
  26611. if (!this._alternateTransformMatrix) {
  26612. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26613. }
  26614. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26615. if (!this._alternateSceneUbo) {
  26616. this._createAlternateUbo();
  26617. }
  26618. if (this._alternateSceneUbo.useUbo) {
  26619. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26620. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26621. this._alternateSceneUbo.update();
  26622. }
  26623. };
  26624. /**
  26625. * Gets the uniform buffer used to store scene data
  26626. * @returns a UniformBuffer
  26627. */
  26628. Scene.prototype.getSceneUniformBuffer = function () {
  26629. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26630. };
  26631. /**
  26632. * Gets an unique (relatively to the current scene) Id
  26633. * @returns an unique number for the scene
  26634. */
  26635. Scene.prototype.getUniqueId = function () {
  26636. var result = Scene._uniqueIdCounter;
  26637. Scene._uniqueIdCounter++;
  26638. return result;
  26639. };
  26640. /**
  26641. * Add a mesh to the list of scene's meshes
  26642. * @param newMesh defines the mesh to add
  26643. * @param recursive if all child meshes should also be added to the scene
  26644. */
  26645. Scene.prototype.addMesh = function (newMesh, recursive) {
  26646. var _this = this;
  26647. if (recursive === void 0) { recursive = false; }
  26648. this.meshes.push(newMesh);
  26649. //notify the collision coordinator
  26650. if (this.collisionCoordinator) {
  26651. this.collisionCoordinator.onMeshAdded(newMesh);
  26652. }
  26653. newMesh._resyncLightSources();
  26654. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26655. if (recursive) {
  26656. newMesh.getChildMeshes().forEach(function (m) {
  26657. _this.addMesh(m);
  26658. });
  26659. }
  26660. };
  26661. /**
  26662. * Remove a mesh for the list of scene's meshes
  26663. * @param toRemove defines the mesh to remove
  26664. * @param recursive if all child meshes should also be removed from the scene
  26665. * @returns the index where the mesh was in the mesh list
  26666. */
  26667. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26668. var _this = this;
  26669. if (recursive === void 0) { recursive = false; }
  26670. var index = this.meshes.indexOf(toRemove);
  26671. if (index !== -1) {
  26672. // Remove from the scene if mesh found
  26673. this.meshes.splice(index, 1);
  26674. }
  26675. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26676. if (recursive) {
  26677. toRemove.getChildMeshes().forEach(function (m) {
  26678. _this.removeMesh(m);
  26679. });
  26680. }
  26681. return index;
  26682. };
  26683. /**
  26684. * Add a transform node to the list of scene's transform nodes
  26685. * @param newTransformNode defines the transform node to add
  26686. */
  26687. Scene.prototype.addTransformNode = function (newTransformNode) {
  26688. this.transformNodes.push(newTransformNode);
  26689. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26690. };
  26691. /**
  26692. * Remove a transform node for the list of scene's transform nodes
  26693. * @param toRemove defines the transform node to remove
  26694. * @returns the index where the transform node was in the transform node list
  26695. */
  26696. Scene.prototype.removeTransformNode = function (toRemove) {
  26697. var index = this.transformNodes.indexOf(toRemove);
  26698. if (index !== -1) {
  26699. // Remove from the scene if found
  26700. this.transformNodes.splice(index, 1);
  26701. }
  26702. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26703. return index;
  26704. };
  26705. /**
  26706. * Remove a skeleton for the list of scene's skeletons
  26707. * @param toRemove defines the skeleton to remove
  26708. * @returns the index where the skeleton was in the skeleton list
  26709. */
  26710. Scene.prototype.removeSkeleton = function (toRemove) {
  26711. var index = this.skeletons.indexOf(toRemove);
  26712. if (index !== -1) {
  26713. // Remove from the scene if found
  26714. this.skeletons.splice(index, 1);
  26715. }
  26716. return index;
  26717. };
  26718. /**
  26719. * Remove a morph target for the list of scene's morph targets
  26720. * @param toRemove defines the morph target to remove
  26721. * @returns the index where the morph target was in the morph target list
  26722. */
  26723. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26724. var index = this.morphTargetManagers.indexOf(toRemove);
  26725. if (index !== -1) {
  26726. // Remove from the scene if found
  26727. this.morphTargetManagers.splice(index, 1);
  26728. }
  26729. return index;
  26730. };
  26731. /**
  26732. * Remove a light for the list of scene's lights
  26733. * @param toRemove defines the light to remove
  26734. * @returns the index where the light was in the light list
  26735. */
  26736. Scene.prototype.removeLight = function (toRemove) {
  26737. var index = this.lights.indexOf(toRemove);
  26738. if (index !== -1) {
  26739. // Remove from meshes
  26740. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26741. var mesh = _a[_i];
  26742. mesh._removeLightSource(toRemove);
  26743. }
  26744. // Remove from the scene if mesh found
  26745. this.lights.splice(index, 1);
  26746. this.sortLightsByPriority();
  26747. }
  26748. this.onLightRemovedObservable.notifyObservers(toRemove);
  26749. return index;
  26750. };
  26751. /**
  26752. * Remove a camera for the list of scene's cameras
  26753. * @param toRemove defines the camera to remove
  26754. * @returns the index where the camera was in the camera list
  26755. */
  26756. Scene.prototype.removeCamera = function (toRemove) {
  26757. var index = this.cameras.indexOf(toRemove);
  26758. if (index !== -1) {
  26759. // Remove from the scene if mesh found
  26760. this.cameras.splice(index, 1);
  26761. }
  26762. // Remove from activeCameras
  26763. var index2 = this.activeCameras.indexOf(toRemove);
  26764. if (index2 !== -1) {
  26765. // Remove from the scene if mesh found
  26766. this.activeCameras.splice(index2, 1);
  26767. }
  26768. // Reset the activeCamera
  26769. if (this.activeCamera === toRemove) {
  26770. if (this.cameras.length > 0) {
  26771. this.activeCamera = this.cameras[0];
  26772. }
  26773. else {
  26774. this.activeCamera = null;
  26775. }
  26776. }
  26777. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26778. return index;
  26779. };
  26780. /**
  26781. * Remove a particle system for the list of scene's particle systems
  26782. * @param toRemove defines the particle system to remove
  26783. * @returns the index where the particle system was in the particle system list
  26784. */
  26785. Scene.prototype.removeParticleSystem = function (toRemove) {
  26786. var index = this.particleSystems.indexOf(toRemove);
  26787. if (index !== -1) {
  26788. this.particleSystems.splice(index, 1);
  26789. }
  26790. return index;
  26791. };
  26792. /**
  26793. * Remove a animation for the list of scene's animations
  26794. * @param toRemove defines the animation to remove
  26795. * @returns the index where the animation was in the animation list
  26796. */
  26797. Scene.prototype.removeAnimation = function (toRemove) {
  26798. var index = this.animations.indexOf(toRemove);
  26799. if (index !== -1) {
  26800. this.animations.splice(index, 1);
  26801. }
  26802. return index;
  26803. };
  26804. /**
  26805. * Removes the given animation group from this scene.
  26806. * @param toRemove The animation group to remove
  26807. * @returns The index of the removed animation group
  26808. */
  26809. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26810. var index = this.animationGroups.indexOf(toRemove);
  26811. if (index !== -1) {
  26812. this.animationGroups.splice(index, 1);
  26813. }
  26814. return index;
  26815. };
  26816. /**
  26817. * Removes the given multi-material from this scene.
  26818. * @param toRemove The multi-material to remove
  26819. * @returns The index of the removed multi-material
  26820. */
  26821. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26822. var index = this.multiMaterials.indexOf(toRemove);
  26823. if (index !== -1) {
  26824. this.multiMaterials.splice(index, 1);
  26825. }
  26826. return index;
  26827. };
  26828. /**
  26829. * Removes the given material from this scene.
  26830. * @param toRemove The material to remove
  26831. * @returns The index of the removed material
  26832. */
  26833. Scene.prototype.removeMaterial = function (toRemove) {
  26834. var index = this.materials.indexOf(toRemove);
  26835. if (index !== -1) {
  26836. this.materials.splice(index, 1);
  26837. }
  26838. return index;
  26839. };
  26840. /**
  26841. * Removes the given action manager from this scene.
  26842. * @param toRemove The action manager to remove
  26843. * @returns The index of the removed action manager
  26844. */
  26845. Scene.prototype.removeActionManager = function (toRemove) {
  26846. var index = this.actionManagers.indexOf(toRemove);
  26847. if (index !== -1) {
  26848. this.actionManagers.splice(index, 1);
  26849. }
  26850. return index;
  26851. };
  26852. /**
  26853. * Removes the given texture from this scene.
  26854. * @param toRemove The texture to remove
  26855. * @returns The index of the removed texture
  26856. */
  26857. Scene.prototype.removeTexture = function (toRemove) {
  26858. var index = this.textures.indexOf(toRemove);
  26859. if (index !== -1) {
  26860. this.textures.splice(index, 1);
  26861. }
  26862. return index;
  26863. };
  26864. /**
  26865. * Adds the given light to this scene
  26866. * @param newLight The light to add
  26867. */
  26868. Scene.prototype.addLight = function (newLight) {
  26869. this.lights.push(newLight);
  26870. this.sortLightsByPriority();
  26871. // Add light to all meshes (To support if the light is removed and then readded)
  26872. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26873. var mesh = _a[_i];
  26874. if (mesh._lightSources.indexOf(newLight) === -1) {
  26875. mesh._lightSources.push(newLight);
  26876. mesh._resyncLightSources();
  26877. }
  26878. }
  26879. this.onNewLightAddedObservable.notifyObservers(newLight);
  26880. };
  26881. /**
  26882. * Sorts the list list based on light priorities
  26883. */
  26884. Scene.prototype.sortLightsByPriority = function () {
  26885. if (this.requireLightSorting) {
  26886. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26887. }
  26888. };
  26889. /**
  26890. * Adds the given camera to this scene
  26891. * @param newCamera The camera to add
  26892. */
  26893. Scene.prototype.addCamera = function (newCamera) {
  26894. this.cameras.push(newCamera);
  26895. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26896. };
  26897. /**
  26898. * Adds the given skeleton to this scene
  26899. * @param newSkeleton The skeleton to add
  26900. */
  26901. Scene.prototype.addSkeleton = function (newSkeleton) {
  26902. this.skeletons.push(newSkeleton);
  26903. };
  26904. /**
  26905. * Adds the given particle system to this scene
  26906. * @param newParticleSystem The particle system to add
  26907. */
  26908. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26909. this.particleSystems.push(newParticleSystem);
  26910. };
  26911. /**
  26912. * Adds the given animation to this scene
  26913. * @param newAnimation The animation to add
  26914. */
  26915. Scene.prototype.addAnimation = function (newAnimation) {
  26916. this.animations.push(newAnimation);
  26917. };
  26918. /**
  26919. * Adds the given animation group to this scene.
  26920. * @param newAnimationGroup The animation group to add
  26921. */
  26922. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26923. this.animationGroups.push(newAnimationGroup);
  26924. };
  26925. /**
  26926. * Adds the given multi-material to this scene
  26927. * @param newMultiMaterial The multi-material to add
  26928. */
  26929. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26930. this.multiMaterials.push(newMultiMaterial);
  26931. };
  26932. /**
  26933. * Adds the given material to this scene
  26934. * @param newMaterial The material to add
  26935. */
  26936. Scene.prototype.addMaterial = function (newMaterial) {
  26937. this.materials.push(newMaterial);
  26938. };
  26939. /**
  26940. * Adds the given morph target to this scene
  26941. * @param newMorphTargetManager The morph target to add
  26942. */
  26943. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26944. this.morphTargetManagers.push(newMorphTargetManager);
  26945. };
  26946. /**
  26947. * Adds the given geometry to this scene
  26948. * @param newGeometry The geometry to add
  26949. */
  26950. Scene.prototype.addGeometry = function (newGeometry) {
  26951. this.geometries.push(newGeometry);
  26952. };
  26953. /**
  26954. * Adds the given action manager to this scene
  26955. * @param newActionManager The action manager to add
  26956. */
  26957. Scene.prototype.addActionManager = function (newActionManager) {
  26958. this.actionManagers.push(newActionManager);
  26959. };
  26960. /**
  26961. * Adds the given texture to this scene.
  26962. * @param newTexture The texture to add
  26963. */
  26964. Scene.prototype.addTexture = function (newTexture) {
  26965. this.textures.push(newTexture);
  26966. };
  26967. /**
  26968. * Switch active camera
  26969. * @param newCamera defines the new active camera
  26970. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26971. */
  26972. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26973. if (attachControl === void 0) { attachControl = true; }
  26974. var canvas = this._engine.getRenderingCanvas();
  26975. if (!canvas) {
  26976. return;
  26977. }
  26978. if (this.activeCamera) {
  26979. this.activeCamera.detachControl(canvas);
  26980. }
  26981. this.activeCamera = newCamera;
  26982. if (attachControl) {
  26983. newCamera.attachControl(canvas);
  26984. }
  26985. };
  26986. /**
  26987. * sets the active camera of the scene using its ID
  26988. * @param id defines the camera's ID
  26989. * @return the new active camera or null if none found.
  26990. */
  26991. Scene.prototype.setActiveCameraByID = function (id) {
  26992. var camera = this.getCameraByID(id);
  26993. if (camera) {
  26994. this.activeCamera = camera;
  26995. return camera;
  26996. }
  26997. return null;
  26998. };
  26999. /**
  27000. * sets the active camera of the scene using its name
  27001. * @param name defines the camera's name
  27002. * @returns the new active camera or null if none found.
  27003. */
  27004. Scene.prototype.setActiveCameraByName = function (name) {
  27005. var camera = this.getCameraByName(name);
  27006. if (camera) {
  27007. this.activeCamera = camera;
  27008. return camera;
  27009. }
  27010. return null;
  27011. };
  27012. /**
  27013. * get an animation group using its name
  27014. * @param name defines the material's name
  27015. * @return the animation group or null if none found.
  27016. */
  27017. Scene.prototype.getAnimationGroupByName = function (name) {
  27018. for (var index = 0; index < this.animationGroups.length; index++) {
  27019. if (this.animationGroups[index].name === name) {
  27020. return this.animationGroups[index];
  27021. }
  27022. }
  27023. return null;
  27024. };
  27025. /**
  27026. * get a material using its id
  27027. * @param id defines the material's ID
  27028. * @return the material or null if none found.
  27029. */
  27030. Scene.prototype.getMaterialByID = function (id) {
  27031. for (var index = 0; index < this.materials.length; index++) {
  27032. if (this.materials[index].id === id) {
  27033. return this.materials[index];
  27034. }
  27035. }
  27036. return null;
  27037. };
  27038. /**
  27039. * Gets a material using its name
  27040. * @param name defines the material's name
  27041. * @return the material or null if none found.
  27042. */
  27043. Scene.prototype.getMaterialByName = function (name) {
  27044. for (var index = 0; index < this.materials.length; index++) {
  27045. if (this.materials[index].name === name) {
  27046. return this.materials[index];
  27047. }
  27048. }
  27049. return null;
  27050. };
  27051. /**
  27052. * Gets a camera using its id
  27053. * @param id defines the id to look for
  27054. * @returns the camera or null if not found
  27055. */
  27056. Scene.prototype.getCameraByID = function (id) {
  27057. for (var index = 0; index < this.cameras.length; index++) {
  27058. if (this.cameras[index].id === id) {
  27059. return this.cameras[index];
  27060. }
  27061. }
  27062. return null;
  27063. };
  27064. /**
  27065. * Gets a camera using its unique id
  27066. * @param uniqueId defines the unique id to look for
  27067. * @returns the camera or null if not found
  27068. */
  27069. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27070. for (var index = 0; index < this.cameras.length; index++) {
  27071. if (this.cameras[index].uniqueId === uniqueId) {
  27072. return this.cameras[index];
  27073. }
  27074. }
  27075. return null;
  27076. };
  27077. /**
  27078. * Gets a camera using its name
  27079. * @param name defines the camera's name
  27080. * @return the camera or null if none found.
  27081. */
  27082. Scene.prototype.getCameraByName = function (name) {
  27083. for (var index = 0; index < this.cameras.length; index++) {
  27084. if (this.cameras[index].name === name) {
  27085. return this.cameras[index];
  27086. }
  27087. }
  27088. return null;
  27089. };
  27090. /**
  27091. * Gets a bone using its id
  27092. * @param id defines the bone's id
  27093. * @return the bone or null if not found
  27094. */
  27095. Scene.prototype.getBoneByID = function (id) {
  27096. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27097. var skeleton = this.skeletons[skeletonIndex];
  27098. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27099. if (skeleton.bones[boneIndex].id === id) {
  27100. return skeleton.bones[boneIndex];
  27101. }
  27102. }
  27103. }
  27104. return null;
  27105. };
  27106. /**
  27107. * Gets a bone using its id
  27108. * @param name defines the bone's name
  27109. * @return the bone or null if not found
  27110. */
  27111. Scene.prototype.getBoneByName = function (name) {
  27112. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27113. var skeleton = this.skeletons[skeletonIndex];
  27114. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27115. if (skeleton.bones[boneIndex].name === name) {
  27116. return skeleton.bones[boneIndex];
  27117. }
  27118. }
  27119. }
  27120. return null;
  27121. };
  27122. /**
  27123. * Gets a light node using its name
  27124. * @param name defines the the light's name
  27125. * @return the light or null if none found.
  27126. */
  27127. Scene.prototype.getLightByName = function (name) {
  27128. for (var index = 0; index < this.lights.length; index++) {
  27129. if (this.lights[index].name === name) {
  27130. return this.lights[index];
  27131. }
  27132. }
  27133. return null;
  27134. };
  27135. /**
  27136. * Gets a light node using its id
  27137. * @param id defines the light's id
  27138. * @return the light or null if none found.
  27139. */
  27140. Scene.prototype.getLightByID = function (id) {
  27141. for (var index = 0; index < this.lights.length; index++) {
  27142. if (this.lights[index].id === id) {
  27143. return this.lights[index];
  27144. }
  27145. }
  27146. return null;
  27147. };
  27148. /**
  27149. * Gets a light node using its scene-generated unique ID
  27150. * @param uniqueId defines the light's unique id
  27151. * @return the light or null if none found.
  27152. */
  27153. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27154. for (var index = 0; index < this.lights.length; index++) {
  27155. if (this.lights[index].uniqueId === uniqueId) {
  27156. return this.lights[index];
  27157. }
  27158. }
  27159. return null;
  27160. };
  27161. /**
  27162. * Gets a particle system by id
  27163. * @param id defines the particle system id
  27164. * @return the corresponding system or null if none found
  27165. */
  27166. Scene.prototype.getParticleSystemByID = function (id) {
  27167. for (var index = 0; index < this.particleSystems.length; index++) {
  27168. if (this.particleSystems[index].id === id) {
  27169. return this.particleSystems[index];
  27170. }
  27171. }
  27172. return null;
  27173. };
  27174. /**
  27175. * Gets a geometry using its ID
  27176. * @param id defines the geometry's id
  27177. * @return the geometry or null if none found.
  27178. */
  27179. Scene.prototype.getGeometryByID = function (id) {
  27180. for (var index = 0; index < this.geometries.length; index++) {
  27181. if (this.geometries[index].id === id) {
  27182. return this.geometries[index];
  27183. }
  27184. }
  27185. return null;
  27186. };
  27187. /**
  27188. * Add a new geometry to this scene
  27189. * @param geometry defines the geometry to be added to the scene.
  27190. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27191. * @return a boolean defining if the geometry was added or not
  27192. */
  27193. Scene.prototype.pushGeometry = function (geometry, force) {
  27194. if (!force && this.getGeometryByID(geometry.id)) {
  27195. return false;
  27196. }
  27197. this.geometries.push(geometry);
  27198. //notify the collision coordinator
  27199. if (this.collisionCoordinator) {
  27200. this.collisionCoordinator.onGeometryAdded(geometry);
  27201. }
  27202. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27203. return true;
  27204. };
  27205. /**
  27206. * Removes an existing geometry
  27207. * @param geometry defines the geometry to be removed from the scene
  27208. * @return a boolean defining if the geometry was removed or not
  27209. */
  27210. Scene.prototype.removeGeometry = function (geometry) {
  27211. var index = this.geometries.indexOf(geometry);
  27212. if (index > -1) {
  27213. this.geometries.splice(index, 1);
  27214. //notify the collision coordinator
  27215. if (this.collisionCoordinator) {
  27216. this.collisionCoordinator.onGeometryDeleted(geometry);
  27217. }
  27218. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27219. return true;
  27220. }
  27221. return false;
  27222. };
  27223. /**
  27224. * Gets the list of geometries attached to the scene
  27225. * @returns an array of Geometry
  27226. */
  27227. Scene.prototype.getGeometries = function () {
  27228. return this.geometries;
  27229. };
  27230. /**
  27231. * Gets the first added mesh found of a given ID
  27232. * @param id defines the id to search for
  27233. * @return the mesh found or null if not found at all
  27234. */
  27235. Scene.prototype.getMeshByID = function (id) {
  27236. for (var index = 0; index < this.meshes.length; index++) {
  27237. if (this.meshes[index].id === id) {
  27238. return this.meshes[index];
  27239. }
  27240. }
  27241. return null;
  27242. };
  27243. /**
  27244. * Gets a list of meshes using their id
  27245. * @param id defines the id to search for
  27246. * @returns a list of meshes
  27247. */
  27248. Scene.prototype.getMeshesByID = function (id) {
  27249. return this.meshes.filter(function (m) {
  27250. return m.id === id;
  27251. });
  27252. };
  27253. /**
  27254. * Gets the first added transform node found of a given ID
  27255. * @param id defines the id to search for
  27256. * @return the found transform node or null if not found at all.
  27257. */
  27258. Scene.prototype.getTransformNodeByID = function (id) {
  27259. for (var index = 0; index < this.transformNodes.length; index++) {
  27260. if (this.transformNodes[index].id === id) {
  27261. return this.transformNodes[index];
  27262. }
  27263. }
  27264. return null;
  27265. };
  27266. /**
  27267. * Gets a list of transform nodes using their id
  27268. * @param id defines the id to search for
  27269. * @returns a list of transform nodes
  27270. */
  27271. Scene.prototype.getTransformNodesByID = function (id) {
  27272. return this.transformNodes.filter(function (m) {
  27273. return m.id === id;
  27274. });
  27275. };
  27276. /**
  27277. * Gets a mesh with its auto-generated unique id
  27278. * @param uniqueId defines the unique id to search for
  27279. * @return the found mesh or null if not found at all.
  27280. */
  27281. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27282. for (var index = 0; index < this.meshes.length; index++) {
  27283. if (this.meshes[index].uniqueId === uniqueId) {
  27284. return this.meshes[index];
  27285. }
  27286. }
  27287. return null;
  27288. };
  27289. /**
  27290. * Gets a the last added mesh using a given id
  27291. * @param id defines the id to search for
  27292. * @return the found mesh or null if not found at all.
  27293. */
  27294. Scene.prototype.getLastMeshByID = function (id) {
  27295. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27296. if (this.meshes[index].id === id) {
  27297. return this.meshes[index];
  27298. }
  27299. }
  27300. return null;
  27301. };
  27302. /**
  27303. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27304. * @param id defines the id to search for
  27305. * @return the found node or null if not found at all
  27306. */
  27307. Scene.prototype.getLastEntryByID = function (id) {
  27308. var index;
  27309. for (index = this.meshes.length - 1; index >= 0; index--) {
  27310. if (this.meshes[index].id === id) {
  27311. return this.meshes[index];
  27312. }
  27313. }
  27314. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27315. if (this.transformNodes[index].id === id) {
  27316. return this.transformNodes[index];
  27317. }
  27318. }
  27319. for (index = this.cameras.length - 1; index >= 0; index--) {
  27320. if (this.cameras[index].id === id) {
  27321. return this.cameras[index];
  27322. }
  27323. }
  27324. for (index = this.lights.length - 1; index >= 0; index--) {
  27325. if (this.lights[index].id === id) {
  27326. return this.lights[index];
  27327. }
  27328. }
  27329. return null;
  27330. };
  27331. /**
  27332. * Gets a node (Mesh, Camera, Light) using a given id
  27333. * @param id defines the id to search for
  27334. * @return the found node or null if not found at all
  27335. */
  27336. Scene.prototype.getNodeByID = function (id) {
  27337. var mesh = this.getMeshByID(id);
  27338. if (mesh) {
  27339. return mesh;
  27340. }
  27341. var light = this.getLightByID(id);
  27342. if (light) {
  27343. return light;
  27344. }
  27345. var camera = this.getCameraByID(id);
  27346. if (camera) {
  27347. return camera;
  27348. }
  27349. var bone = this.getBoneByID(id);
  27350. return bone;
  27351. };
  27352. /**
  27353. * Gets a node (Mesh, Camera, Light) using a given name
  27354. * @param name defines the name to search for
  27355. * @return the found node or null if not found at all.
  27356. */
  27357. Scene.prototype.getNodeByName = function (name) {
  27358. var mesh = this.getMeshByName(name);
  27359. if (mesh) {
  27360. return mesh;
  27361. }
  27362. var light = this.getLightByName(name);
  27363. if (light) {
  27364. return light;
  27365. }
  27366. var camera = this.getCameraByName(name);
  27367. if (camera) {
  27368. return camera;
  27369. }
  27370. var bone = this.getBoneByName(name);
  27371. return bone;
  27372. };
  27373. /**
  27374. * Gets a mesh using a given name
  27375. * @param name defines the name to search for
  27376. * @return the found mesh or null if not found at all.
  27377. */
  27378. Scene.prototype.getMeshByName = function (name) {
  27379. for (var index = 0; index < this.meshes.length; index++) {
  27380. if (this.meshes[index].name === name) {
  27381. return this.meshes[index];
  27382. }
  27383. }
  27384. return null;
  27385. };
  27386. /**
  27387. * Gets a transform node using a given name
  27388. * @param name defines the name to search for
  27389. * @return the found transform node or null if not found at all.
  27390. */
  27391. Scene.prototype.getTransformNodeByName = function (name) {
  27392. for (var index = 0; index < this.transformNodes.length; index++) {
  27393. if (this.transformNodes[index].name === name) {
  27394. return this.transformNodes[index];
  27395. }
  27396. }
  27397. return null;
  27398. };
  27399. /**
  27400. * Gets a sound using a given name
  27401. * @param name defines the name to search for
  27402. * @return the found sound or null if not found at all.
  27403. */
  27404. Scene.prototype.getSoundByName = function (name) {
  27405. var index;
  27406. if (BABYLON.AudioEngine) {
  27407. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27408. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27409. return this.mainSoundTrack.soundCollection[index];
  27410. }
  27411. }
  27412. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27413. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27414. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27415. return this.soundTracks[sdIndex].soundCollection[index];
  27416. }
  27417. }
  27418. }
  27419. }
  27420. return null;
  27421. };
  27422. /**
  27423. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27424. * @param id defines the id to search for
  27425. * @return the found skeleton or null if not found at all.
  27426. */
  27427. Scene.prototype.getLastSkeletonByID = function (id) {
  27428. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27429. if (this.skeletons[index].id === id) {
  27430. return this.skeletons[index];
  27431. }
  27432. }
  27433. return null;
  27434. };
  27435. /**
  27436. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27437. * @param id defines the id to search for
  27438. * @return the found skeleton or null if not found at all.
  27439. */
  27440. Scene.prototype.getSkeletonById = function (id) {
  27441. for (var index = 0; index < this.skeletons.length; index++) {
  27442. if (this.skeletons[index].id === id) {
  27443. return this.skeletons[index];
  27444. }
  27445. }
  27446. return null;
  27447. };
  27448. /**
  27449. * Gets a skeleton using a given name
  27450. * @param name defines the name to search for
  27451. * @return the found skeleton or null if not found at all.
  27452. */
  27453. Scene.prototype.getSkeletonByName = function (name) {
  27454. for (var index = 0; index < this.skeletons.length; index++) {
  27455. if (this.skeletons[index].name === name) {
  27456. return this.skeletons[index];
  27457. }
  27458. }
  27459. return null;
  27460. };
  27461. /**
  27462. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27463. * @param id defines the id to search for
  27464. * @return the found morph target manager or null if not found at all.
  27465. */
  27466. Scene.prototype.getMorphTargetManagerById = function (id) {
  27467. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27468. if (this.morphTargetManagers[index].uniqueId === id) {
  27469. return this.morphTargetManagers[index];
  27470. }
  27471. }
  27472. return null;
  27473. };
  27474. /**
  27475. * Gets a boolean indicating if the given mesh is active
  27476. * @param mesh defines the mesh to look for
  27477. * @returns true if the mesh is in the active list
  27478. */
  27479. Scene.prototype.isActiveMesh = function (mesh) {
  27480. return (this._activeMeshes.indexOf(mesh) !== -1);
  27481. };
  27482. Object.defineProperty(Scene.prototype, "uid", {
  27483. /**
  27484. * Return a unique id as a string which can serve as an identifier for the scene
  27485. */
  27486. get: function () {
  27487. if (!this._uid) {
  27488. this._uid = BABYLON.Tools.RandomId();
  27489. }
  27490. return this._uid;
  27491. },
  27492. enumerable: true,
  27493. configurable: true
  27494. });
  27495. /**
  27496. * Add an externaly attached data from its key.
  27497. * This method call will fail and return false, if such key already exists.
  27498. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27499. * @param key the unique key that identifies the data
  27500. * @param data the data object to associate to the key for this Engine instance
  27501. * @return true if no such key were already present and the data was added successfully, false otherwise
  27502. */
  27503. Scene.prototype.addExternalData = function (key, data) {
  27504. if (!this._externalData) {
  27505. this._externalData = new BABYLON.StringDictionary();
  27506. }
  27507. return this._externalData.add(key, data);
  27508. };
  27509. /**
  27510. * Get an externaly attached data from its key
  27511. * @param key the unique key that identifies the data
  27512. * @return the associated data, if present (can be null), or undefined if not present
  27513. */
  27514. Scene.prototype.getExternalData = function (key) {
  27515. if (!this._externalData) {
  27516. return null;
  27517. }
  27518. return this._externalData.get(key);
  27519. };
  27520. /**
  27521. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27522. * @param key the unique key that identifies the data
  27523. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27524. * @return the associated data, can be null if the factory returned null.
  27525. */
  27526. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27527. if (!this._externalData) {
  27528. this._externalData = new BABYLON.StringDictionary();
  27529. }
  27530. return this._externalData.getOrAddWithFactory(key, factory);
  27531. };
  27532. /**
  27533. * Remove an externaly attached data from the Engine instance
  27534. * @param key the unique key that identifies the data
  27535. * @return true if the data was successfully removed, false if it doesn't exist
  27536. */
  27537. Scene.prototype.removeExternalData = function (key) {
  27538. return this._externalData.remove(key);
  27539. };
  27540. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27541. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27542. if (mesh.showSubMeshesBoundingBox) {
  27543. var boundingInfo = subMesh.getBoundingInfo();
  27544. if (boundingInfo !== null && boundingInfo !== undefined) {
  27545. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27546. }
  27547. }
  27548. var material = subMesh.getMaterial();
  27549. if (material !== null && material !== undefined) {
  27550. // Render targets
  27551. if (material.getRenderTargetTextures !== undefined) {
  27552. if (this._processedMaterials.indexOf(material) === -1) {
  27553. this._processedMaterials.push(material);
  27554. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27555. }
  27556. }
  27557. // Dispatch
  27558. this._activeIndices.addCount(subMesh.indexCount, false);
  27559. this._renderingManager.dispatch(subMesh, mesh, material);
  27560. }
  27561. }
  27562. };
  27563. /**
  27564. * Clear the processed materials smart array preventing retention point in material dispose.
  27565. */
  27566. Scene.prototype.freeProcessedMaterials = function () {
  27567. this._processedMaterials.dispose();
  27568. };
  27569. /**
  27570. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27571. */
  27572. Scene.prototype.freeActiveMeshes = function () {
  27573. this._activeMeshes.dispose();
  27574. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27575. this.activeCamera._activeMeshes.dispose();
  27576. }
  27577. if (this.activeCameras) {
  27578. for (var i = 0; i < this.activeCameras.length; i++) {
  27579. var activeCamera = this.activeCameras[i];
  27580. if (activeCamera && activeCamera._activeMeshes) {
  27581. activeCamera._activeMeshes.dispose();
  27582. }
  27583. }
  27584. }
  27585. };
  27586. /**
  27587. * Clear the info related to rendering groups preventing retention points during dispose.
  27588. */
  27589. Scene.prototype.freeRenderingGroups = function () {
  27590. if (this._renderingManager) {
  27591. this._renderingManager.freeRenderingGroups();
  27592. }
  27593. if (this.textures) {
  27594. for (var i = 0; i < this.textures.length; i++) {
  27595. var texture = this.textures[i];
  27596. if (texture && texture.renderList) {
  27597. texture.freeRenderingGroups();
  27598. }
  27599. }
  27600. }
  27601. };
  27602. /** @hidden */
  27603. Scene.prototype._isInIntermediateRendering = function () {
  27604. return this._intermediateRendering;
  27605. };
  27606. /**
  27607. * Defines the current active mesh candidate provider
  27608. * @param provider defines the provider to use
  27609. */
  27610. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27611. this._activeMeshCandidateProvider = provider;
  27612. };
  27613. /**
  27614. * Gets the current active mesh candidate provider
  27615. * @returns the current active mesh candidate provider
  27616. */
  27617. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27618. return this._activeMeshCandidateProvider;
  27619. };
  27620. /**
  27621. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27622. * @returns the current scene
  27623. */
  27624. Scene.prototype.freezeActiveMeshes = function () {
  27625. if (!this.activeCamera) {
  27626. return this;
  27627. }
  27628. if (!this._frustumPlanes) {
  27629. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27630. }
  27631. this._evaluateActiveMeshes();
  27632. this._activeMeshesFrozen = true;
  27633. return this;
  27634. };
  27635. /**
  27636. * Use this function to restart evaluating active meshes on every frame
  27637. * @returns the current scene
  27638. */
  27639. Scene.prototype.unfreezeActiveMeshes = function () {
  27640. this._activeMeshesFrozen = false;
  27641. return this;
  27642. };
  27643. Scene.prototype._evaluateActiveMeshes = function () {
  27644. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27645. return;
  27646. }
  27647. if (!this.activeCamera) {
  27648. return;
  27649. }
  27650. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27651. this.activeCamera._activeMeshes.reset();
  27652. this._activeMeshes.reset();
  27653. this._renderingManager.reset();
  27654. this._processedMaterials.reset();
  27655. this._activeParticleSystems.reset();
  27656. this._activeSkeletons.reset();
  27657. this._softwareSkinnedMeshes.reset();
  27658. if (this._boundingBoxRenderer) {
  27659. this._boundingBoxRenderer.reset();
  27660. }
  27661. // Meshes
  27662. var meshes;
  27663. var len;
  27664. var checkIsEnabled = true;
  27665. // Determine mesh candidates
  27666. if (this._activeMeshCandidateProvider !== undefined) {
  27667. // Use _activeMeshCandidateProvider
  27668. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27669. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27670. if (meshes !== undefined) {
  27671. len = meshes.length;
  27672. }
  27673. else {
  27674. len = 0;
  27675. }
  27676. }
  27677. else if (this._selectionOctree !== undefined) {
  27678. // Octree
  27679. var selection = this._selectionOctree.select(this._frustumPlanes);
  27680. meshes = selection.data;
  27681. len = selection.length;
  27682. }
  27683. else {
  27684. // Full scene traversal
  27685. len = this.meshes.length;
  27686. meshes = this.meshes;
  27687. }
  27688. // Check each mesh
  27689. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27690. mesh = meshes[meshIndex];
  27691. if (mesh.isBlocked) {
  27692. continue;
  27693. }
  27694. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27695. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27696. continue;
  27697. }
  27698. mesh.computeWorldMatrix();
  27699. // Intersections
  27700. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27701. this._meshesForIntersections.pushNoDuplicate(mesh);
  27702. }
  27703. // Switch to current LOD
  27704. meshLOD = mesh.getLOD(this.activeCamera);
  27705. if (meshLOD === undefined || meshLOD === null) {
  27706. continue;
  27707. }
  27708. mesh._preActivate();
  27709. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27710. this._activeMeshes.push(mesh);
  27711. this.activeCamera._activeMeshes.push(mesh);
  27712. mesh._activate(this._renderId);
  27713. if (meshLOD !== mesh) {
  27714. meshLOD._activate(this._renderId);
  27715. }
  27716. this._activeMesh(mesh, meshLOD);
  27717. }
  27718. }
  27719. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27720. // Particle systems
  27721. if (this.particlesEnabled) {
  27722. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27723. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27724. var particleSystem = this.particleSystems[particleIndex];
  27725. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27726. continue;
  27727. }
  27728. var emitter = particleSystem.emitter;
  27729. if (!emitter.position || emitter.isEnabled()) {
  27730. this._activeParticleSystems.push(particleSystem);
  27731. particleSystem.animate();
  27732. this._renderingManager.dispatchParticles(particleSystem);
  27733. }
  27734. }
  27735. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27736. }
  27737. };
  27738. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27739. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27740. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27741. mesh.skeleton.prepare();
  27742. }
  27743. if (!mesh.computeBonesUsingShaders) {
  27744. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27745. }
  27746. }
  27747. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27748. var boundingInfo = sourceMesh.getBoundingInfo();
  27749. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27750. }
  27751. if (mesh !== undefined && mesh !== null
  27752. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27753. // Submeshes Octrees
  27754. var len;
  27755. var subMeshes;
  27756. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27757. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27758. len = intersections.length;
  27759. subMeshes = intersections.data;
  27760. }
  27761. else {
  27762. subMeshes = mesh.subMeshes;
  27763. len = subMeshes.length;
  27764. }
  27765. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27766. subMesh = subMeshes[subIndex];
  27767. this._evaluateSubMesh(subMesh, mesh);
  27768. }
  27769. }
  27770. };
  27771. /**
  27772. * Update the transform matrix to update from the current active camera
  27773. * @param force defines a boolean used to force the update even if cache is up to date
  27774. */
  27775. Scene.prototype.updateTransformMatrix = function (force) {
  27776. if (!this.activeCamera) {
  27777. return;
  27778. }
  27779. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27780. };
  27781. /**
  27782. * 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)
  27783. * @param alternateCamera defines the camera to use
  27784. */
  27785. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27786. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27787. };
  27788. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27789. if (camera && camera._skipRendering) {
  27790. return;
  27791. }
  27792. var engine = this._engine;
  27793. this.activeCamera = camera;
  27794. if (!this.activeCamera)
  27795. throw new Error("Active camera not set");
  27796. // Viewport
  27797. engine.setViewport(this.activeCamera.viewport);
  27798. // Camera
  27799. this.resetCachedMaterial();
  27800. this._renderId++;
  27801. this.updateTransformMatrix();
  27802. if (camera._alternateCamera) {
  27803. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27804. this._alternateRendering = true;
  27805. }
  27806. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27807. // Meshes
  27808. this._evaluateActiveMeshes();
  27809. // Software skinning
  27810. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27811. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27812. mesh.applySkeleton(mesh.skeleton);
  27813. }
  27814. // Render targets
  27815. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27816. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27817. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27818. }
  27819. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27820. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27821. }
  27822. if (this.renderTargetsEnabled) {
  27823. this._intermediateRendering = true;
  27824. if (this._renderTargets.length > 0) {
  27825. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27826. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27827. var renderTarget = this._renderTargets.data[renderIndex];
  27828. if (renderTarget._shouldRender()) {
  27829. this._renderId++;
  27830. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27831. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27832. }
  27833. }
  27834. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27835. this._renderId++;
  27836. }
  27837. for (var _i = 0, _a = this._cameraDrawRenderTargetStage; _i < _a.length; _i++) {
  27838. var step = _a[_i];
  27839. step.action(this.activeCamera);
  27840. }
  27841. this._intermediateRendering = false;
  27842. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  27843. }
  27844. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27845. // Prepare Frame
  27846. if (this.postProcessManager) {
  27847. this.postProcessManager._prepareFrame();
  27848. }
  27849. // Before Camera Draw
  27850. for (var _b = 0, _c = this._beforeCameraDrawStage; _b < _c.length; _b++) {
  27851. var step = _c[_b];
  27852. step.action(this.activeCamera);
  27853. }
  27854. // Render
  27855. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27856. this._renderingManager.render(null, null, true, true);
  27857. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27858. // After Camera Draw
  27859. for (var _d = 0, _e = this._afterCameraDrawStage; _d < _e.length; _d++) {
  27860. var step = _e[_d];
  27861. step.action(this.activeCamera);
  27862. }
  27863. // Bounding boxes
  27864. if (this._boundingBoxRenderer) {
  27865. this._boundingBoxRenderer.render();
  27866. }
  27867. // Finalize frame
  27868. if (this.postProcessManager) {
  27869. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27870. }
  27871. // Reset some special arrays
  27872. this._renderTargets.reset();
  27873. this._alternateRendering = false;
  27874. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27875. };
  27876. Scene.prototype._processSubCameras = function (camera) {
  27877. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27878. this._renderForCamera(camera);
  27879. return;
  27880. }
  27881. // rig cameras
  27882. for (var index = 0; index < camera._rigCameras.length; index++) {
  27883. this._renderForCamera(camera._rigCameras[index], camera);
  27884. }
  27885. this.activeCamera = camera;
  27886. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27887. };
  27888. Scene.prototype._checkIntersections = function () {
  27889. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27890. var sourceMesh = this._meshesForIntersections.data[index];
  27891. if (!sourceMesh.actionManager) {
  27892. continue;
  27893. }
  27894. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27895. var action = sourceMesh.actionManager.actions[actionIndex];
  27896. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27897. var parameters = action.getTriggerParameter();
  27898. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27899. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27900. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27901. if (areIntersecting && currentIntersectionInProgress === -1) {
  27902. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27903. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27904. sourceMesh._intersectionsInProgress.push(otherMesh);
  27905. }
  27906. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27907. sourceMesh._intersectionsInProgress.push(otherMesh);
  27908. }
  27909. }
  27910. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27911. //They intersected, and now they don't.
  27912. //is this trigger an exit trigger? execute an event.
  27913. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27914. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27915. }
  27916. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27917. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27918. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27919. return otherMesh === parameterMesh;
  27920. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27921. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27922. }
  27923. }
  27924. }
  27925. }
  27926. }
  27927. };
  27928. /**
  27929. * Render the scene
  27930. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27931. */
  27932. Scene.prototype.render = function (updateCameras) {
  27933. if (updateCameras === void 0) { updateCameras = true; }
  27934. if (this.isDisposed) {
  27935. return;
  27936. }
  27937. // Register components that have been associated lately to the scene.
  27938. this._registerTransientComponents();
  27939. this._activeParticles.fetchNewFrame();
  27940. this._totalVertices.fetchNewFrame();
  27941. this._activeIndices.fetchNewFrame();
  27942. this._activeBones.fetchNewFrame();
  27943. this._meshesForIntersections.reset();
  27944. this.resetCachedMaterial();
  27945. this.onBeforeAnimationsObservable.notifyObservers(this);
  27946. // Actions
  27947. if (this.actionManager) {
  27948. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27949. }
  27950. //Simplification Queue
  27951. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27952. this.simplificationQueue.executeNext();
  27953. }
  27954. if (this._engine.isDeterministicLockStep()) {
  27955. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27956. var defaultFPS = (60.0 / 1000.0);
  27957. var defaultFrameTime = 1000 / 60; // frame time in MS
  27958. if (this._physicsEngine) {
  27959. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27960. }
  27961. var stepsTaken = 0;
  27962. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27963. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27964. internalSteps = Math.min(internalSteps, maxSubSteps);
  27965. do {
  27966. this.onBeforeStepObservable.notifyObservers(this);
  27967. // Animations
  27968. this._animationRatio = defaultFrameTime * defaultFPS;
  27969. this._animate();
  27970. this.onAfterAnimationsObservable.notifyObservers(this);
  27971. // Physics
  27972. if (this._physicsEngine) {
  27973. this.onBeforePhysicsObservable.notifyObservers(this);
  27974. this._physicsEngine._step(defaultFrameTime / 1000);
  27975. this.onAfterPhysicsObservable.notifyObservers(this);
  27976. }
  27977. this.onAfterStepObservable.notifyObservers(this);
  27978. this._currentStepId++;
  27979. stepsTaken++;
  27980. deltaTime -= defaultFrameTime;
  27981. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27982. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27983. }
  27984. else {
  27985. // Animations
  27986. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27987. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27988. this._animate();
  27989. this.onAfterAnimationsObservable.notifyObservers(this);
  27990. // Physics
  27991. if (this._physicsEngine) {
  27992. this.onBeforePhysicsObservable.notifyObservers(this);
  27993. this._physicsEngine._step(deltaTime / 1000.0);
  27994. this.onAfterPhysicsObservable.notifyObservers(this);
  27995. }
  27996. }
  27997. // update gamepad manager
  27998. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27999. this._gamepadManager._checkGamepadsStatus();
  28000. }
  28001. // Update Cameras
  28002. if (updateCameras) {
  28003. if (this.activeCameras.length > 0) {
  28004. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28005. var camera = this.activeCameras[cameraIndex];
  28006. camera.update();
  28007. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28008. // rig cameras
  28009. for (var index = 0; index < camera._rigCameras.length; index++) {
  28010. camera._rigCameras[index].update();
  28011. }
  28012. }
  28013. }
  28014. }
  28015. else if (this.activeCamera) {
  28016. this.activeCamera.update();
  28017. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28018. // rig cameras
  28019. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28020. this.activeCamera._rigCameras[index].update();
  28021. }
  28022. }
  28023. }
  28024. }
  28025. // Before render
  28026. this.onBeforeRenderObservable.notifyObservers(this);
  28027. // Customs render targets
  28028. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28029. var engine = this.getEngine();
  28030. var currentActiveCamera = this.activeCamera;
  28031. if (this.renderTargetsEnabled) {
  28032. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28033. this._intermediateRendering = true;
  28034. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28035. var renderTarget = this.customRenderTargets[customIndex];
  28036. if (renderTarget._shouldRender()) {
  28037. this._renderId++;
  28038. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28039. if (!this.activeCamera)
  28040. throw new Error("Active camera not set");
  28041. // Viewport
  28042. engine.setViewport(this.activeCamera.viewport);
  28043. // Camera
  28044. this.updateTransformMatrix();
  28045. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28046. }
  28047. }
  28048. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28049. this._intermediateRendering = false;
  28050. this._renderId++;
  28051. }
  28052. // Restore back buffer
  28053. if (this.customRenderTargets.length > 0) {
  28054. engine.restoreDefaultFramebuffer();
  28055. }
  28056. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28057. this.activeCamera = currentActiveCamera;
  28058. // Procedural textures
  28059. if (this.proceduralTexturesEnabled) {
  28060. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28061. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  28062. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  28063. if (proceduralTexture._shouldRender()) {
  28064. proceduralTexture.render();
  28065. }
  28066. }
  28067. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28068. }
  28069. // Clear
  28070. if (this.autoClearDepthAndStencil || this.autoClear) {
  28071. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28072. }
  28073. // Shadows
  28074. if (this.shadowsEnabled) {
  28075. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28076. var light = this.lights[lightIndex];
  28077. var shadowGenerator = light.getShadowGenerator();
  28078. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28079. var shadowMap = (shadowGenerator.getShadowMap());
  28080. if (this.textures.indexOf(shadowMap) !== -1) {
  28081. this._renderTargets.push(shadowMap);
  28082. }
  28083. }
  28084. }
  28085. }
  28086. // Depth renderer
  28087. for (var key in this._depthRenderer) {
  28088. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28089. }
  28090. // Geometry renderer
  28091. if (this._geometryBufferRenderer) {
  28092. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28093. }
  28094. // RenderPipeline
  28095. if (this._postProcessRenderPipelineManager) {
  28096. this._postProcessRenderPipelineManager.update();
  28097. }
  28098. // Multi-cameras?
  28099. if (this.activeCameras.length > 0) {
  28100. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28101. if (cameraIndex > 0) {
  28102. this._engine.clear(null, false, true, true);
  28103. }
  28104. this._processSubCameras(this.activeCameras[cameraIndex]);
  28105. }
  28106. }
  28107. else {
  28108. if (!this.activeCamera) {
  28109. throw new Error("No camera defined");
  28110. }
  28111. this._processSubCameras(this.activeCamera);
  28112. }
  28113. // Intersection checks
  28114. this._checkIntersections();
  28115. // Update the audio listener attached to the camera
  28116. if (BABYLON.AudioEngine) {
  28117. this._updateAudioParameters();
  28118. }
  28119. // After render
  28120. if (this.afterRender) {
  28121. this.afterRender();
  28122. }
  28123. this.onAfterRenderObservable.notifyObservers(this);
  28124. // Cleaning
  28125. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28126. var data = this._toBeDisposed.data[index];
  28127. if (data) {
  28128. data.dispose();
  28129. }
  28130. this._toBeDisposed[index] = null;
  28131. }
  28132. this._toBeDisposed.reset();
  28133. if (this.dumpNextRenderTargets) {
  28134. this.dumpNextRenderTargets = false;
  28135. }
  28136. this._activeBones.addCount(0, true);
  28137. this._activeIndices.addCount(0, true);
  28138. this._activeParticles.addCount(0, true);
  28139. };
  28140. Scene.prototype._updateAudioParameters = function () {
  28141. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28142. return;
  28143. }
  28144. var listeningCamera;
  28145. var audioEngine = BABYLON.Engine.audioEngine;
  28146. if (this.activeCameras.length > 0) {
  28147. listeningCamera = this.activeCameras[0];
  28148. }
  28149. else {
  28150. listeningCamera = this.activeCamera;
  28151. }
  28152. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28153. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28154. // for VR cameras
  28155. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28156. listeningCamera = listeningCamera.rigCameras[0];
  28157. }
  28158. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28159. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28160. cameraDirection.normalize();
  28161. // To avoid some errors on GearVR
  28162. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28163. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28164. }
  28165. var i;
  28166. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28167. var sound = this.mainSoundTrack.soundCollection[i];
  28168. if (sound.useCustomAttenuation) {
  28169. sound.updateDistanceFromListener();
  28170. }
  28171. }
  28172. for (i = 0; i < this.soundTracks.length; i++) {
  28173. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28174. sound = this.soundTracks[i].soundCollection[j];
  28175. if (sound.useCustomAttenuation) {
  28176. sound.updateDistanceFromListener();
  28177. }
  28178. }
  28179. }
  28180. }
  28181. };
  28182. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28183. // Audio
  28184. /**
  28185. * Gets or sets if audio support is enabled
  28186. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28187. */
  28188. get: function () {
  28189. return this._audioEnabled;
  28190. },
  28191. set: function (value) {
  28192. this._audioEnabled = value;
  28193. if (BABYLON.AudioEngine) {
  28194. if (this._audioEnabled) {
  28195. this._enableAudio();
  28196. }
  28197. else {
  28198. this._disableAudio();
  28199. }
  28200. }
  28201. },
  28202. enumerable: true,
  28203. configurable: true
  28204. });
  28205. Scene.prototype._disableAudio = function () {
  28206. var i;
  28207. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28208. this.mainSoundTrack.soundCollection[i].pause();
  28209. }
  28210. for (i = 0; i < this.soundTracks.length; i++) {
  28211. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28212. this.soundTracks[i].soundCollection[j].pause();
  28213. }
  28214. }
  28215. };
  28216. Scene.prototype._enableAudio = function () {
  28217. var i;
  28218. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28219. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28220. this.mainSoundTrack.soundCollection[i].play();
  28221. }
  28222. }
  28223. for (i = 0; i < this.soundTracks.length; i++) {
  28224. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28225. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28226. this.soundTracks[i].soundCollection[j].play();
  28227. }
  28228. }
  28229. }
  28230. };
  28231. Object.defineProperty(Scene.prototype, "headphone", {
  28232. /**
  28233. * Gets or sets if audio will be output to headphones
  28234. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28235. */
  28236. get: function () {
  28237. return this._headphone;
  28238. },
  28239. set: function (value) {
  28240. this._headphone = value;
  28241. if (BABYLON.AudioEngine) {
  28242. if (this._headphone) {
  28243. this._switchAudioModeForHeadphones();
  28244. }
  28245. else {
  28246. this._switchAudioModeForNormalSpeakers();
  28247. }
  28248. }
  28249. },
  28250. enumerable: true,
  28251. configurable: true
  28252. });
  28253. Scene.prototype._switchAudioModeForHeadphones = function () {
  28254. this.mainSoundTrack.switchPanningModelToHRTF();
  28255. for (var i = 0; i < this.soundTracks.length; i++) {
  28256. this.soundTracks[i].switchPanningModelToHRTF();
  28257. }
  28258. };
  28259. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28260. this.mainSoundTrack.switchPanningModelToEqualPower();
  28261. for (var i = 0; i < this.soundTracks.length; i++) {
  28262. this.soundTracks[i].switchPanningModelToEqualPower();
  28263. }
  28264. };
  28265. /**
  28266. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28267. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28268. * @returns the created depth renderer
  28269. */
  28270. Scene.prototype.enableDepthRenderer = function (camera) {
  28271. camera = camera || this.activeCamera;
  28272. if (!camera) {
  28273. throw "No camera available to enable depth renderer";
  28274. }
  28275. if (!this._depthRenderer[camera.id]) {
  28276. var textureType = 0;
  28277. if (this._engine.getCaps().textureHalfFloatRender) {
  28278. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28279. }
  28280. else if (this._engine.getCaps().textureFloatRender) {
  28281. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28282. }
  28283. else {
  28284. throw "Depth renderer does not support int texture type";
  28285. }
  28286. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28287. }
  28288. return this._depthRenderer[camera.id];
  28289. };
  28290. /**
  28291. * Disables a depth renderer for a given camera
  28292. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28293. */
  28294. Scene.prototype.disableDepthRenderer = function (camera) {
  28295. camera = camera || this.activeCamera;
  28296. if (!camera || !this._depthRenderer[camera.id]) {
  28297. return;
  28298. }
  28299. this._depthRenderer[camera.id].dispose();
  28300. delete this._depthRenderer[camera.id];
  28301. };
  28302. /**
  28303. * Enables a GeometryBufferRender and associates it with the scene
  28304. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28305. * @returns the GeometryBufferRenderer
  28306. */
  28307. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28308. if (ratio === void 0) { ratio = 1; }
  28309. if (this._geometryBufferRenderer) {
  28310. return this._geometryBufferRenderer;
  28311. }
  28312. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28313. if (!this._geometryBufferRenderer.isSupported) {
  28314. this._geometryBufferRenderer = null;
  28315. }
  28316. return this._geometryBufferRenderer;
  28317. };
  28318. /**
  28319. * Disables the GeometryBufferRender associated with the scene
  28320. */
  28321. Scene.prototype.disableGeometryBufferRenderer = function () {
  28322. if (!this._geometryBufferRenderer) {
  28323. return;
  28324. }
  28325. this._geometryBufferRenderer.dispose();
  28326. this._geometryBufferRenderer = null;
  28327. };
  28328. /**
  28329. * Freeze all materials
  28330. * A frozen material will not be updatable but should be faster to render
  28331. */
  28332. Scene.prototype.freezeMaterials = function () {
  28333. for (var i = 0; i < this.materials.length; i++) {
  28334. this.materials[i].freeze();
  28335. }
  28336. };
  28337. /**
  28338. * Unfreeze all materials
  28339. * A frozen material will not be updatable but should be faster to render
  28340. */
  28341. Scene.prototype.unfreezeMaterials = function () {
  28342. for (var i = 0; i < this.materials.length; i++) {
  28343. this.materials[i].unfreeze();
  28344. }
  28345. };
  28346. /**
  28347. * Releases all held ressources
  28348. */
  28349. Scene.prototype.dispose = function () {
  28350. this.beforeRender = null;
  28351. this.afterRender = null;
  28352. this.skeletons = [];
  28353. this.morphTargetManagers = [];
  28354. this._transientComponents = [];
  28355. this._isReadyForMeshStage.clear();
  28356. this._cameraDrawRenderTargetStage.clear();
  28357. this._beforeCameraDrawStage.clear();
  28358. this._afterCameraDrawStage.clear();
  28359. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  28360. var component = _a[_i];
  28361. component.dispose();
  28362. }
  28363. this.importedMeshesFiles = new Array();
  28364. this.stopAllAnimations();
  28365. this.resetCachedMaterial();
  28366. for (var key in this._depthRenderer) {
  28367. this._depthRenderer[key].dispose();
  28368. }
  28369. if (this._gamepadManager) {
  28370. this._gamepadManager.dispose();
  28371. this._gamepadManager = null;
  28372. }
  28373. // Smart arrays
  28374. if (this.activeCamera) {
  28375. this.activeCamera._activeMeshes.dispose();
  28376. this.activeCamera = null;
  28377. }
  28378. this._activeMeshes.dispose();
  28379. this._renderingManager.dispose();
  28380. this._processedMaterials.dispose();
  28381. this._activeParticleSystems.dispose();
  28382. this._activeSkeletons.dispose();
  28383. this._softwareSkinnedMeshes.dispose();
  28384. this._renderTargets.dispose();
  28385. this._registeredForLateAnimationBindings.dispose();
  28386. if (this._boundingBoxRenderer) {
  28387. this._boundingBoxRenderer.dispose();
  28388. }
  28389. this._meshesForIntersections.dispose();
  28390. this._toBeDisposed.dispose();
  28391. // Abort active requests
  28392. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  28393. var request = _c[_b];
  28394. request.abort();
  28395. }
  28396. // Debug layer
  28397. if (this._debugLayer) {
  28398. this._debugLayer.hide();
  28399. }
  28400. // Events
  28401. this.onDisposeObservable.notifyObservers(this);
  28402. this.onDisposeObservable.clear();
  28403. this.onBeforeRenderObservable.clear();
  28404. this.onAfterRenderObservable.clear();
  28405. this.onBeforeRenderTargetsRenderObservable.clear();
  28406. this.onAfterRenderTargetsRenderObservable.clear();
  28407. this.onAfterStepObservable.clear();
  28408. this.onBeforeStepObservable.clear();
  28409. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28410. this.onAfterActiveMeshesEvaluationObservable.clear();
  28411. this.onBeforeParticlesRenderingObservable.clear();
  28412. this.onAfterParticlesRenderingObservable.clear();
  28413. this.onBeforeSpritesRenderingObservable.clear();
  28414. this.onAfterSpritesRenderingObservable.clear();
  28415. this.onBeforeDrawPhaseObservable.clear();
  28416. this.onAfterDrawPhaseObservable.clear();
  28417. this.onBeforePhysicsObservable.clear();
  28418. this.onAfterPhysicsObservable.clear();
  28419. this.onBeforeAnimationsObservable.clear();
  28420. this.onAfterAnimationsObservable.clear();
  28421. this.onDataLoadedObservable.clear();
  28422. this.detachControl();
  28423. // Release sounds & sounds tracks
  28424. if (BABYLON.AudioEngine) {
  28425. this.disposeSounds();
  28426. }
  28427. // VR Helper
  28428. if (this.VRHelper) {
  28429. this.VRHelper.dispose();
  28430. }
  28431. // Detach cameras
  28432. var canvas = this._engine.getRenderingCanvas();
  28433. if (canvas) {
  28434. var index;
  28435. for (index = 0; index < this.cameras.length; index++) {
  28436. this.cameras[index].detachControl(canvas);
  28437. }
  28438. }
  28439. // Release animation groups
  28440. while (this.animationGroups.length) {
  28441. this.animationGroups[0].dispose();
  28442. }
  28443. // Release lights
  28444. while (this.lights.length) {
  28445. this.lights[0].dispose();
  28446. }
  28447. // Release meshes
  28448. while (this.meshes.length) {
  28449. this.meshes[0].dispose(true);
  28450. }
  28451. while (this.transformNodes.length) {
  28452. this.removeTransformNode(this.transformNodes[0]);
  28453. }
  28454. // Release cameras
  28455. while (this.cameras.length) {
  28456. this.cameras[0].dispose();
  28457. }
  28458. // Release materials
  28459. if (this.defaultMaterial) {
  28460. this.defaultMaterial.dispose();
  28461. }
  28462. while (this.multiMaterials.length) {
  28463. this.multiMaterials[0].dispose();
  28464. }
  28465. while (this.materials.length) {
  28466. this.materials[0].dispose();
  28467. }
  28468. // Release particles
  28469. while (this.particleSystems.length) {
  28470. this.particleSystems[0].dispose();
  28471. }
  28472. // Release sprites
  28473. while (this.spriteManagers.length) {
  28474. this.spriteManagers[0].dispose();
  28475. }
  28476. // Release postProcesses
  28477. while (this.postProcesses.length) {
  28478. this.postProcesses[0].dispose();
  28479. }
  28480. // Release textures
  28481. while (this.textures.length) {
  28482. this.textures[0].dispose();
  28483. }
  28484. // Release UBO
  28485. this._sceneUbo.dispose();
  28486. if (this._alternateSceneUbo) {
  28487. this._alternateSceneUbo.dispose();
  28488. }
  28489. // Post-processes
  28490. this.postProcessManager.dispose();
  28491. if (this._postProcessRenderPipelineManager) {
  28492. this._postProcessRenderPipelineManager.dispose();
  28493. }
  28494. // Physics
  28495. if (this._physicsEngine) {
  28496. this.disablePhysicsEngine();
  28497. }
  28498. // Remove from engine
  28499. index = this._engine.scenes.indexOf(this);
  28500. if (index > -1) {
  28501. this._engine.scenes.splice(index, 1);
  28502. }
  28503. this._engine.wipeCaches(true);
  28504. this._isDisposed = true;
  28505. };
  28506. Object.defineProperty(Scene.prototype, "isDisposed", {
  28507. /**
  28508. * Gets if the scene is already disposed
  28509. */
  28510. get: function () {
  28511. return this._isDisposed;
  28512. },
  28513. enumerable: true,
  28514. configurable: true
  28515. });
  28516. /**
  28517. * Releases sounds & soundtracks
  28518. */
  28519. Scene.prototype.disposeSounds = function () {
  28520. if (!this._mainSoundTrack) {
  28521. return;
  28522. }
  28523. this.mainSoundTrack.dispose();
  28524. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28525. this.soundTracks[scIndex].dispose();
  28526. }
  28527. };
  28528. /**
  28529. * Call this function to reduce memory footprint of the scene.
  28530. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28531. */
  28532. Scene.prototype.clearCachedVertexData = function () {
  28533. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28534. var mesh = this.meshes[meshIndex];
  28535. var geometry = mesh.geometry;
  28536. if (geometry) {
  28537. geometry._indices = [];
  28538. for (var vbName in geometry._vertexBuffers) {
  28539. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28540. continue;
  28541. }
  28542. geometry._vertexBuffers[vbName]._buffer._data = null;
  28543. }
  28544. }
  28545. }
  28546. };
  28547. /**
  28548. * This function will remove the local cached buffer data from texture.
  28549. * It will save memory but will prevent the texture from being rebuilt
  28550. */
  28551. Scene.prototype.cleanCachedTextureBuffer = function () {
  28552. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28553. var baseTexture = _a[_i];
  28554. var buffer = baseTexture._buffer;
  28555. if (buffer) {
  28556. baseTexture._buffer = null;
  28557. }
  28558. }
  28559. };
  28560. // Octrees
  28561. /**
  28562. * Get the world extend vectors with an optional filter
  28563. *
  28564. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28565. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28566. */
  28567. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28568. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28569. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28570. filterPredicate = filterPredicate || (function () { return true; });
  28571. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28572. mesh.computeWorldMatrix(true);
  28573. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28574. return;
  28575. }
  28576. var boundingInfo = mesh.getBoundingInfo();
  28577. var minBox = boundingInfo.boundingBox.minimumWorld;
  28578. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28579. BABYLON.Tools.CheckExtends(minBox, min, max);
  28580. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28581. });
  28582. return {
  28583. min: min,
  28584. max: max
  28585. };
  28586. };
  28587. /**
  28588. * Creates or updates the octree used to boost selection (picking)
  28589. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28590. * @param maxCapacity defines the maximum capacity per leaf
  28591. * @param maxDepth defines the maximum depth of the octree
  28592. * @returns an octree of AbstractMesh
  28593. */
  28594. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28595. if (maxCapacity === void 0) { maxCapacity = 64; }
  28596. if (maxDepth === void 0) { maxDepth = 2; }
  28597. if (!this._selectionOctree) {
  28598. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28599. }
  28600. var worldExtends = this.getWorldExtends();
  28601. // Update octree
  28602. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28603. return this._selectionOctree;
  28604. };
  28605. // Picking
  28606. /**
  28607. * Creates a ray that can be used to pick in the scene
  28608. * @param x defines the x coordinate of the origin (on-screen)
  28609. * @param y defines the y coordinate of the origin (on-screen)
  28610. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28611. * @param camera defines the camera to use for the picking
  28612. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28613. * @returns a Ray
  28614. */
  28615. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28616. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28617. var result = BABYLON.Ray.Zero();
  28618. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28619. return result;
  28620. };
  28621. /**
  28622. * Creates a ray that can be used to pick in the scene
  28623. * @param x defines the x coordinate of the origin (on-screen)
  28624. * @param y defines the y coordinate of the origin (on-screen)
  28625. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28626. * @param result defines the ray where to store the picking ray
  28627. * @param camera defines the camera to use for the picking
  28628. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28629. * @returns the current scene
  28630. */
  28631. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28632. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28633. var engine = this._engine;
  28634. if (!camera) {
  28635. if (!this.activeCamera)
  28636. throw new Error("Active camera not set");
  28637. camera = this.activeCamera;
  28638. }
  28639. var cameraViewport = camera.viewport;
  28640. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28641. // Moving coordinates to local viewport world
  28642. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28643. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28644. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28645. return this;
  28646. };
  28647. /**
  28648. * Creates a ray that can be used to pick in the scene
  28649. * @param x defines the x coordinate of the origin (on-screen)
  28650. * @param y defines the y coordinate of the origin (on-screen)
  28651. * @param camera defines the camera to use for the picking
  28652. * @returns a Ray
  28653. */
  28654. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28655. var result = BABYLON.Ray.Zero();
  28656. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28657. return result;
  28658. };
  28659. /**
  28660. * Creates a ray that can be used to pick in the scene
  28661. * @param x defines the x coordinate of the origin (on-screen)
  28662. * @param y defines the y coordinate of the origin (on-screen)
  28663. * @param result defines the ray where to store the picking ray
  28664. * @param camera defines the camera to use for the picking
  28665. * @returns the current scene
  28666. */
  28667. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28668. if (!BABYLON.PickingInfo) {
  28669. return this;
  28670. }
  28671. var engine = this._engine;
  28672. if (!camera) {
  28673. if (!this.activeCamera)
  28674. throw new Error("Active camera not set");
  28675. camera = this.activeCamera;
  28676. }
  28677. var cameraViewport = camera.viewport;
  28678. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28679. var identity = BABYLON.Matrix.Identity();
  28680. // Moving coordinates to local viewport world
  28681. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28682. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28683. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28684. return this;
  28685. };
  28686. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28687. if (!BABYLON.PickingInfo) {
  28688. return null;
  28689. }
  28690. var pickingInfo = null;
  28691. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28692. var mesh = this.meshes[meshIndex];
  28693. if (predicate) {
  28694. if (!predicate(mesh)) {
  28695. continue;
  28696. }
  28697. }
  28698. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28699. continue;
  28700. }
  28701. var world = mesh.getWorldMatrix();
  28702. var ray = rayFunction(world);
  28703. var result = mesh.intersects(ray, fastCheck);
  28704. if (!result || !result.hit)
  28705. continue;
  28706. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28707. continue;
  28708. pickingInfo = result;
  28709. if (fastCheck) {
  28710. break;
  28711. }
  28712. }
  28713. return pickingInfo || new BABYLON.PickingInfo();
  28714. };
  28715. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28716. if (!BABYLON.PickingInfo) {
  28717. return null;
  28718. }
  28719. var pickingInfos = new Array();
  28720. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28721. var mesh = this.meshes[meshIndex];
  28722. if (predicate) {
  28723. if (!predicate(mesh)) {
  28724. continue;
  28725. }
  28726. }
  28727. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28728. continue;
  28729. }
  28730. var world = mesh.getWorldMatrix();
  28731. var ray = rayFunction(world);
  28732. var result = mesh.intersects(ray, false);
  28733. if (!result || !result.hit)
  28734. continue;
  28735. pickingInfos.push(result);
  28736. }
  28737. return pickingInfos;
  28738. };
  28739. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28740. if (!BABYLON.PickingInfo) {
  28741. return null;
  28742. }
  28743. var pickingInfo = null;
  28744. if (!camera) {
  28745. if (!this.activeCamera) {
  28746. return null;
  28747. }
  28748. camera = this.activeCamera;
  28749. }
  28750. if (this.spriteManagers.length > 0) {
  28751. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28752. var spriteManager = this.spriteManagers[spriteIndex];
  28753. if (!spriteManager.isPickable) {
  28754. continue;
  28755. }
  28756. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28757. if (!result || !result.hit)
  28758. continue;
  28759. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28760. continue;
  28761. pickingInfo = result;
  28762. if (fastCheck) {
  28763. break;
  28764. }
  28765. }
  28766. }
  28767. return pickingInfo || new BABYLON.PickingInfo();
  28768. };
  28769. /** Launch a ray to try to pick a mesh in the scene
  28770. * @param x position on screen
  28771. * @param y position on screen
  28772. * @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
  28773. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28774. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28775. * @returns a PickingInfo
  28776. */
  28777. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28778. var _this = this;
  28779. if (!BABYLON.PickingInfo) {
  28780. return null;
  28781. }
  28782. var result = this._internalPick(function (world) {
  28783. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28784. return _this._tempPickingRay;
  28785. }, predicate, fastCheck);
  28786. if (result) {
  28787. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28788. }
  28789. return result;
  28790. };
  28791. /** Launch a ray to try to pick a sprite in the scene
  28792. * @param x position on screen
  28793. * @param y position on screen
  28794. * @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
  28795. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28796. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28797. * @returns a PickingInfo
  28798. */
  28799. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28800. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28801. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28802. };
  28803. /** Use the given ray to pick a mesh in the scene
  28804. * @param ray The ray to use to pick meshes
  28805. * @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
  28806. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28807. * @returns a PickingInfo
  28808. */
  28809. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28810. var _this = this;
  28811. var result = this._internalPick(function (world) {
  28812. if (!_this._pickWithRayInverseMatrix) {
  28813. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28814. }
  28815. world.invertToRef(_this._pickWithRayInverseMatrix);
  28816. if (!_this._cachedRayForTransform) {
  28817. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28818. }
  28819. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28820. return _this._cachedRayForTransform;
  28821. }, predicate, fastCheck);
  28822. if (result) {
  28823. result.ray = ray;
  28824. }
  28825. return result;
  28826. };
  28827. /**
  28828. * Launch a ray to try to pick a mesh in the scene
  28829. * @param x X position on screen
  28830. * @param y Y position on screen
  28831. * @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
  28832. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28833. * @returns an array of PickingInfo
  28834. */
  28835. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28836. var _this = this;
  28837. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28838. };
  28839. /**
  28840. * Launch a ray to try to pick a mesh in the scene
  28841. * @param ray Ray to use
  28842. * @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
  28843. * @returns an array of PickingInfo
  28844. */
  28845. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28846. var _this = this;
  28847. return this._internalMultiPick(function (world) {
  28848. if (!_this._pickWithRayInverseMatrix) {
  28849. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28850. }
  28851. world.invertToRef(_this._pickWithRayInverseMatrix);
  28852. if (!_this._cachedRayForTransform) {
  28853. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28854. }
  28855. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28856. return _this._cachedRayForTransform;
  28857. }, predicate);
  28858. };
  28859. /**
  28860. * Force the value of meshUnderPointer
  28861. * @param mesh defines the mesh to use
  28862. */
  28863. Scene.prototype.setPointerOverMesh = function (mesh) {
  28864. if (this._pointerOverMesh === mesh) {
  28865. return;
  28866. }
  28867. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28868. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28869. }
  28870. this._pointerOverMesh = mesh;
  28871. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28872. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28873. }
  28874. };
  28875. /**
  28876. * Gets the mesh under the pointer
  28877. * @returns a Mesh or null if no mesh is under the pointer
  28878. */
  28879. Scene.prototype.getPointerOverMesh = function () {
  28880. return this._pointerOverMesh;
  28881. };
  28882. /**
  28883. * Force the sprite under the pointer
  28884. * @param sprite defines the sprite to use
  28885. */
  28886. Scene.prototype.setPointerOverSprite = function (sprite) {
  28887. if (this._pointerOverSprite === sprite) {
  28888. return;
  28889. }
  28890. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28891. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28892. }
  28893. this._pointerOverSprite = sprite;
  28894. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28895. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28896. }
  28897. };
  28898. /**
  28899. * Gets the sprite under the pointer
  28900. * @returns a Sprite or null if no sprite is under the pointer
  28901. */
  28902. Scene.prototype.getPointerOverSprite = function () {
  28903. return this._pointerOverSprite;
  28904. };
  28905. // Physics
  28906. /**
  28907. * Gets the current physics engine
  28908. * @returns a PhysicsEngine or null if none attached
  28909. */
  28910. Scene.prototype.getPhysicsEngine = function () {
  28911. return this._physicsEngine;
  28912. };
  28913. /**
  28914. * Enables physics to the current scene
  28915. * @param gravity defines the scene's gravity for the physics engine
  28916. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28917. * @return a boolean indicating if the physics engine was initialized
  28918. */
  28919. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28920. if (gravity === void 0) { gravity = null; }
  28921. if (this._physicsEngine) {
  28922. return true;
  28923. }
  28924. try {
  28925. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28926. return true;
  28927. }
  28928. catch (e) {
  28929. BABYLON.Tools.Error(e.message);
  28930. return false;
  28931. }
  28932. };
  28933. /**
  28934. * Disables and disposes the physics engine associated with the scene
  28935. */
  28936. Scene.prototype.disablePhysicsEngine = function () {
  28937. if (!this._physicsEngine) {
  28938. return;
  28939. }
  28940. this._physicsEngine.dispose();
  28941. this._physicsEngine = null;
  28942. };
  28943. /**
  28944. * Gets a boolean indicating if there is an active physics engine
  28945. * @returns a boolean indicating if there is an active physics engine
  28946. */
  28947. Scene.prototype.isPhysicsEnabled = function () {
  28948. return this._physicsEngine !== undefined;
  28949. };
  28950. /**
  28951. * Deletes a physics compound impostor
  28952. * @param compound defines the compound to delete
  28953. */
  28954. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28955. var mesh = compound.parts[0].mesh;
  28956. if (mesh.physicsImpostor) {
  28957. mesh.physicsImpostor.dispose( /*true*/);
  28958. mesh.physicsImpostor = null;
  28959. }
  28960. };
  28961. // Misc.
  28962. /** @hidden */
  28963. Scene.prototype._rebuildGeometries = function () {
  28964. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  28965. var geometry = _a[_i];
  28966. geometry._rebuild();
  28967. }
  28968. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28969. var mesh = _c[_b];
  28970. mesh._rebuild();
  28971. }
  28972. if (this.postProcessManager) {
  28973. this.postProcessManager._rebuild();
  28974. }
  28975. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  28976. var component = _e[_d];
  28977. component.rebuild();
  28978. }
  28979. if (this._boundingBoxRenderer) {
  28980. this._boundingBoxRenderer._rebuild();
  28981. }
  28982. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  28983. var system = _g[_f];
  28984. system.rebuild();
  28985. }
  28986. if (this._postProcessRenderPipelineManager) {
  28987. this._postProcessRenderPipelineManager._rebuild();
  28988. }
  28989. };
  28990. /** @hidden */
  28991. Scene.prototype._rebuildTextures = function () {
  28992. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28993. var texture = _a[_i];
  28994. texture._rebuild();
  28995. }
  28996. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28997. };
  28998. /**
  28999. * Creates a default light for the scene.
  29000. * @param replace Whether to replace the existing lights in the scene.
  29001. */
  29002. Scene.prototype.createDefaultLight = function (replace) {
  29003. if (replace === void 0) { replace = false; }
  29004. // Dispose existing light in replace mode.
  29005. if (replace) {
  29006. if (this.lights) {
  29007. for (var i = 0; i < this.lights.length; i++) {
  29008. this.lights[i].dispose();
  29009. }
  29010. }
  29011. }
  29012. // Light
  29013. if (this.lights.length === 0) {
  29014. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  29015. }
  29016. };
  29017. /**
  29018. * Creates a default camera for the scene.
  29019. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  29020. * @param replace Whether to replace the existing active camera in the scene.
  29021. * @param attachCameraControls Whether to attach camera controls to the canvas.
  29022. */
  29023. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  29024. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29025. if (replace === void 0) { replace = false; }
  29026. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29027. // Dispose existing camera in replace mode.
  29028. if (replace) {
  29029. if (this.activeCamera) {
  29030. this.activeCamera.dispose();
  29031. this.activeCamera = null;
  29032. }
  29033. }
  29034. // Camera
  29035. if (!this.activeCamera) {
  29036. var worldExtends = this.getWorldExtends();
  29037. var worldSize = worldExtends.max.subtract(worldExtends.min);
  29038. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  29039. var camera;
  29040. var radius = worldSize.length() * 1.5;
  29041. // empty scene scenario!
  29042. if (!isFinite(radius)) {
  29043. radius = 1;
  29044. worldCenter.copyFromFloats(0, 0, 0);
  29045. }
  29046. if (createArcRotateCamera) {
  29047. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  29048. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  29049. arcRotateCamera.wheelPrecision = 100 / radius;
  29050. camera = arcRotateCamera;
  29051. }
  29052. else {
  29053. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  29054. freeCamera.setTarget(worldCenter);
  29055. camera = freeCamera;
  29056. }
  29057. camera.minZ = radius * 0.01;
  29058. camera.maxZ = radius * 1000;
  29059. camera.speed = radius * 0.2;
  29060. this.activeCamera = camera;
  29061. var canvas = this.getEngine().getRenderingCanvas();
  29062. if (attachCameraControls && canvas) {
  29063. camera.attachControl(canvas);
  29064. }
  29065. }
  29066. };
  29067. /**
  29068. * Creates a default camera and a default light
  29069. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29070. * @param replace defines if the camera and/or light will replace the existing ones
  29071. * @param attachCameraControls defines if attachControl will be called on the new camera
  29072. */
  29073. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29074. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29075. if (replace === void 0) { replace = false; }
  29076. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29077. this.createDefaultLight(replace);
  29078. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29079. };
  29080. /**
  29081. * Creates a new sky box
  29082. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29083. * @param environmentTexture defines the texture to use as environment texture
  29084. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29085. * @param scale defines the overall scale of the skybox
  29086. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29087. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29088. * @returns a new mesh holding the sky box
  29089. */
  29090. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29091. if (pbr === void 0) { pbr = false; }
  29092. if (scale === void 0) { scale = 1000; }
  29093. if (blur === void 0) { blur = 0; }
  29094. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29095. if (!environmentTexture) {
  29096. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29097. return null;
  29098. }
  29099. if (setGlobalEnvTexture) {
  29100. if (environmentTexture) {
  29101. this.environmentTexture = environmentTexture;
  29102. }
  29103. }
  29104. // Skybox
  29105. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29106. if (pbr) {
  29107. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29108. hdrSkyboxMaterial.backFaceCulling = false;
  29109. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29110. if (hdrSkyboxMaterial.reflectionTexture) {
  29111. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29112. }
  29113. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29114. hdrSkyboxMaterial.disableLighting = true;
  29115. hdrSkyboxMaterial.twoSidedLighting = true;
  29116. hdrSkybox.infiniteDistance = true;
  29117. hdrSkybox.material = hdrSkyboxMaterial;
  29118. }
  29119. else {
  29120. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29121. skyboxMaterial.backFaceCulling = false;
  29122. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29123. if (skyboxMaterial.reflectionTexture) {
  29124. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29125. }
  29126. skyboxMaterial.disableLighting = true;
  29127. hdrSkybox.infiniteDistance = true;
  29128. hdrSkybox.material = skyboxMaterial;
  29129. }
  29130. return hdrSkybox;
  29131. };
  29132. /**
  29133. * Creates a new environment
  29134. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29135. * @param options defines the options you can use to configure the environment
  29136. * @returns the new EnvironmentHelper
  29137. */
  29138. Scene.prototype.createDefaultEnvironment = function (options) {
  29139. if (BABYLON.EnvironmentHelper) {
  29140. return new BABYLON.EnvironmentHelper(options, this);
  29141. }
  29142. return null;
  29143. };
  29144. /**
  29145. * Creates a new VREXperienceHelper
  29146. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29147. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29148. * @returns a new VREXperienceHelper
  29149. */
  29150. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29151. if (webVROptions === void 0) { webVROptions = {}; }
  29152. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29153. };
  29154. // Tags
  29155. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29156. if (tagsQuery === undefined) {
  29157. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29158. return list;
  29159. }
  29160. var listByTags = [];
  29161. forEach = forEach || (function (item) { return; });
  29162. for (var i in list) {
  29163. var item = list[i];
  29164. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29165. listByTags.push(item);
  29166. forEach(item);
  29167. }
  29168. }
  29169. return listByTags;
  29170. };
  29171. /**
  29172. * Get a list of meshes by tags
  29173. * @param tagsQuery defines the tags query to use
  29174. * @param forEach defines a predicate used to filter results
  29175. * @returns an array of Mesh
  29176. */
  29177. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29178. return this._getByTags(this.meshes, tagsQuery, forEach);
  29179. };
  29180. /**
  29181. * Get a list of cameras by tags
  29182. * @param tagsQuery defines the tags query to use
  29183. * @param forEach defines a predicate used to filter results
  29184. * @returns an array of Camera
  29185. */
  29186. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29187. return this._getByTags(this.cameras, tagsQuery, forEach);
  29188. };
  29189. /**
  29190. * Get a list of lights by tags
  29191. * @param tagsQuery defines the tags query to use
  29192. * @param forEach defines a predicate used to filter results
  29193. * @returns an array of Light
  29194. */
  29195. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29196. return this._getByTags(this.lights, tagsQuery, forEach);
  29197. };
  29198. /**
  29199. * Get a list of materials by tags
  29200. * @param tagsQuery defines the tags query to use
  29201. * @param forEach defines a predicate used to filter results
  29202. * @returns an array of Material
  29203. */
  29204. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29205. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29206. };
  29207. /**
  29208. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29209. * This allowed control for front to back rendering or reversly depending of the special needs.
  29210. *
  29211. * @param renderingGroupId The rendering group id corresponding to its index
  29212. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29213. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29214. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29215. */
  29216. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29217. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29218. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29219. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29220. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29221. };
  29222. /**
  29223. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29224. *
  29225. * @param renderingGroupId The rendering group id corresponding to its index
  29226. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29227. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29228. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29229. */
  29230. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29231. if (depth === void 0) { depth = true; }
  29232. if (stencil === void 0) { stencil = true; }
  29233. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29234. };
  29235. /**
  29236. * Will flag all materials as dirty to trigger new shader compilation
  29237. * @param flag defines the flag used to specify which material part must be marked as dirty
  29238. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29239. */
  29240. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29241. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29242. var material = _a[_i];
  29243. if (predicate && !predicate(material)) {
  29244. continue;
  29245. }
  29246. material.markAsDirty(flag);
  29247. }
  29248. };
  29249. /** @hidden */
  29250. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29251. var _this = this;
  29252. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29253. this._activeRequests.push(request);
  29254. request.onCompleteObservable.add(function (request) {
  29255. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29256. });
  29257. return request;
  29258. };
  29259. /** @hidden */
  29260. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29261. var _this = this;
  29262. return new Promise(function (resolve, reject) {
  29263. _this._loadFile(url, function (data) {
  29264. resolve(data);
  29265. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29266. reject(exception);
  29267. });
  29268. });
  29269. };
  29270. // Statics
  29271. Scene._FOGMODE_NONE = 0;
  29272. Scene._FOGMODE_EXP = 1;
  29273. Scene._FOGMODE_EXP2 = 2;
  29274. Scene._FOGMODE_LINEAR = 3;
  29275. Scene._uniqueIdCounter = 0;
  29276. /**
  29277. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29278. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29279. */
  29280. Scene.MinDeltaTime = 1.0;
  29281. /**
  29282. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29283. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29284. */
  29285. Scene.MaxDeltaTime = 1000.0;
  29286. /** The distance in pixel that you have to move to prevent some events */
  29287. Scene.DragMovementThreshold = 10; // in pixels
  29288. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29289. Scene.LongPressDelay = 500; // in milliseconds
  29290. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29291. Scene.DoubleClickDelay = 300; // in milliseconds
  29292. /** If you need to check double click without raising a single click at first click, enable this flag */
  29293. Scene.ExclusiveDoubleClickMode = false;
  29294. return Scene;
  29295. }(BABYLON.AbstractScene));
  29296. BABYLON.Scene = Scene;
  29297. })(BABYLON || (BABYLON = {}));
  29298. //# sourceMappingURL=babylon.scene.js.map
  29299. var BABYLON;
  29300. (function (BABYLON) {
  29301. /**
  29302. * Set of assets to keep when moving a scene into an asset container.
  29303. */
  29304. var KeepAssets = /** @class */ (function (_super) {
  29305. __extends(KeepAssets, _super);
  29306. function KeepAssets() {
  29307. return _super !== null && _super.apply(this, arguments) || this;
  29308. }
  29309. return KeepAssets;
  29310. }(BABYLON.AbstractScene));
  29311. BABYLON.KeepAssets = KeepAssets;
  29312. /**
  29313. * Container with a set of assets that can be added or removed from a scene.
  29314. */
  29315. var AssetContainer = /** @class */ (function (_super) {
  29316. __extends(AssetContainer, _super);
  29317. /**
  29318. * Instantiates an AssetContainer.
  29319. * @param scene The scene the AssetContainer belongs to.
  29320. */
  29321. function AssetContainer(scene) {
  29322. var _this = _super.call(this) || this;
  29323. _this.scene = scene;
  29324. return _this;
  29325. }
  29326. /**
  29327. * Adds all the assets from the container to the scene.
  29328. */
  29329. AssetContainer.prototype.addAllToScene = function () {
  29330. var _this = this;
  29331. this.cameras.forEach(function (o) {
  29332. _this.scene.addCamera(o);
  29333. });
  29334. this.lights.forEach(function (o) {
  29335. _this.scene.addLight(o);
  29336. });
  29337. this.meshes.forEach(function (o) {
  29338. _this.scene.addMesh(o);
  29339. });
  29340. this.skeletons.forEach(function (o) {
  29341. _this.scene.addSkeleton(o);
  29342. });
  29343. this.particleSystems.forEach(function (o) {
  29344. _this.scene.addParticleSystem(o);
  29345. });
  29346. this.animations.forEach(function (o) {
  29347. _this.scene.addAnimation(o);
  29348. });
  29349. this.animationGroups.forEach(function (o) {
  29350. _this.scene.addAnimationGroup(o);
  29351. });
  29352. this.multiMaterials.forEach(function (o) {
  29353. _this.scene.addMultiMaterial(o);
  29354. });
  29355. this.materials.forEach(function (o) {
  29356. _this.scene.addMaterial(o);
  29357. });
  29358. this.morphTargetManagers.forEach(function (o) {
  29359. _this.scene.addMorphTargetManager(o);
  29360. });
  29361. this.geometries.forEach(function (o) {
  29362. _this.scene.addGeometry(o);
  29363. });
  29364. this.transformNodes.forEach(function (o) {
  29365. _this.scene.addTransformNode(o);
  29366. });
  29367. this.actionManagers.forEach(function (o) {
  29368. _this.scene.addActionManager(o);
  29369. });
  29370. this.sounds.forEach(function (o) {
  29371. o.play();
  29372. o.autoplay = true;
  29373. _this.scene.mainSoundTrack.AddSound(o);
  29374. });
  29375. this.textures.forEach(function (o) {
  29376. _this.scene.addTexture(o);
  29377. });
  29378. for (var _i = 0, _a = this.scene._components; _i < _a.length; _i++) {
  29379. var component = _a[_i];
  29380. component.addFromContainer(this.scene);
  29381. }
  29382. };
  29383. /**
  29384. * Removes all the assets in the container from the scene
  29385. */
  29386. AssetContainer.prototype.removeAllFromScene = function () {
  29387. var _this = this;
  29388. this.cameras.forEach(function (o) {
  29389. _this.scene.removeCamera(o);
  29390. });
  29391. this.lights.forEach(function (o) {
  29392. _this.scene.removeLight(o);
  29393. });
  29394. this.meshes.forEach(function (o) {
  29395. _this.scene.removeMesh(o);
  29396. });
  29397. this.skeletons.forEach(function (o) {
  29398. _this.scene.removeSkeleton(o);
  29399. });
  29400. this.particleSystems.forEach(function (o) {
  29401. _this.scene.removeParticleSystem(o);
  29402. });
  29403. this.animations.forEach(function (o) {
  29404. _this.scene.removeAnimation(o);
  29405. });
  29406. this.animationGroups.forEach(function (o) {
  29407. _this.scene.removeAnimationGroup(o);
  29408. });
  29409. this.multiMaterials.forEach(function (o) {
  29410. _this.scene.removeMultiMaterial(o);
  29411. });
  29412. this.materials.forEach(function (o) {
  29413. _this.scene.removeMaterial(o);
  29414. });
  29415. this.morphTargetManagers.forEach(function (o) {
  29416. _this.scene.removeMorphTargetManager(o);
  29417. });
  29418. this.geometries.forEach(function (o) {
  29419. _this.scene.removeGeometry(o);
  29420. });
  29421. this.transformNodes.forEach(function (o) {
  29422. _this.scene.removeTransformNode(o);
  29423. });
  29424. this.actionManagers.forEach(function (o) {
  29425. _this.scene.removeActionManager(o);
  29426. });
  29427. this.sounds.forEach(function (o) {
  29428. o.stop();
  29429. o.autoplay = false;
  29430. _this.scene.mainSoundTrack.RemoveSound(o);
  29431. });
  29432. this.textures.forEach(function (o) {
  29433. _this.scene.removeTexture(o);
  29434. });
  29435. for (var _i = 0, _a = this.scene._components; _i < _a.length; _i++) {
  29436. var component = _a[_i];
  29437. component.removeFromContainer(this.scene);
  29438. }
  29439. };
  29440. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29441. if (!sourceAssets) {
  29442. return;
  29443. }
  29444. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29445. var asset = sourceAssets_1[_i];
  29446. var move = true;
  29447. if (keepAssets) {
  29448. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29449. var keepAsset = keepAssets_1[_a];
  29450. if (asset === keepAsset) {
  29451. move = false;
  29452. break;
  29453. }
  29454. }
  29455. }
  29456. if (move) {
  29457. targetAssets.push(asset);
  29458. }
  29459. }
  29460. };
  29461. /**
  29462. * Removes all the assets contained in the scene and adds them to the container.
  29463. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29464. */
  29465. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29466. if (keepAssets === undefined) {
  29467. keepAssets = new KeepAssets();
  29468. }
  29469. for (var key in this) {
  29470. if (this.hasOwnProperty(key)) {
  29471. this[key] = this[key] || [];
  29472. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29473. }
  29474. }
  29475. this.removeAllFromScene();
  29476. };
  29477. /**
  29478. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29479. * @returns the root mesh
  29480. */
  29481. AssetContainer.prototype.createRootMesh = function () {
  29482. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29483. this.meshes.forEach(function (m) {
  29484. if (!m.parent) {
  29485. rootMesh.addChild(m);
  29486. }
  29487. });
  29488. this.meshes.unshift(rootMesh);
  29489. return rootMesh;
  29490. };
  29491. return AssetContainer;
  29492. }(BABYLON.AbstractScene));
  29493. BABYLON.AssetContainer = AssetContainer;
  29494. })(BABYLON || (BABYLON = {}));
  29495. //# sourceMappingURL=babylon.assetContainer.js.map
  29496. var BABYLON;
  29497. (function (BABYLON) {
  29498. var Buffer = /** @class */ (function () {
  29499. /**
  29500. * Constructor
  29501. * @param engine the engine
  29502. * @param data the data to use for this buffer
  29503. * @param updatable whether the data is updatable
  29504. * @param stride the stride (optional)
  29505. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29506. * @param instanced whether the buffer is instanced (optional)
  29507. * @param useBytes set to true if the stride in in bytes (optional)
  29508. */
  29509. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29510. if (stride === void 0) { stride = 0; }
  29511. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29512. if (instanced === void 0) { instanced = false; }
  29513. if (useBytes === void 0) { useBytes = false; }
  29514. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29515. this._engine = engine.getScene().getEngine();
  29516. }
  29517. else {
  29518. this._engine = engine;
  29519. }
  29520. this._updatable = updatable;
  29521. this._instanced = instanced;
  29522. this._data = data;
  29523. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29524. if (!postponeInternalCreation) { // by default
  29525. this.create();
  29526. }
  29527. }
  29528. /**
  29529. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29530. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29531. * @param offset defines offset in the buffer (0 by default)
  29532. * @param size defines the size in floats of attributes (position is 3 for instance)
  29533. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29534. * @param instanced defines if the vertex buffer contains indexed data
  29535. * @param useBytes defines if the offset and stride are in bytes
  29536. * @returns the new vertex buffer
  29537. */
  29538. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29539. if (useBytes === void 0) { useBytes = false; }
  29540. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29541. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29542. // a lot of these parameters are ignored as they are overriden by the buffer
  29543. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29544. };
  29545. // Properties
  29546. Buffer.prototype.isUpdatable = function () {
  29547. return this._updatable;
  29548. };
  29549. Buffer.prototype.getData = function () {
  29550. return this._data;
  29551. };
  29552. Buffer.prototype.getBuffer = function () {
  29553. return this._buffer;
  29554. };
  29555. /**
  29556. * Gets the stride in float32 units (i.e. byte stride / 4).
  29557. * May not be an integer if the byte stride is not divisible by 4.
  29558. * DEPRECATED. Use byteStride instead.
  29559. * @returns the stride in float32 units
  29560. */
  29561. Buffer.prototype.getStrideSize = function () {
  29562. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29563. };
  29564. // Methods
  29565. Buffer.prototype.create = function (data) {
  29566. if (data === void 0) { data = null; }
  29567. if (!data && this._buffer) {
  29568. return; // nothing to do
  29569. }
  29570. data = data || this._data;
  29571. if (!data) {
  29572. return;
  29573. }
  29574. if (!this._buffer) { // create buffer
  29575. if (this._updatable) {
  29576. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29577. this._data = data;
  29578. }
  29579. else {
  29580. this._buffer = this._engine.createVertexBuffer(data);
  29581. }
  29582. }
  29583. else if (this._updatable) { // update buffer
  29584. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29585. this._data = data;
  29586. }
  29587. };
  29588. Buffer.prototype._rebuild = function () {
  29589. this._buffer = null;
  29590. this.create(this._data);
  29591. };
  29592. Buffer.prototype.update = function (data) {
  29593. this.create(data);
  29594. };
  29595. /**
  29596. * Updates the data directly.
  29597. * @param data the new data
  29598. * @param offset the new offset
  29599. * @param vertexCount the vertex count (optional)
  29600. * @param useBytes set to true if the offset is in bytes
  29601. */
  29602. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29603. if (useBytes === void 0) { useBytes = false; }
  29604. if (!this._buffer) {
  29605. return;
  29606. }
  29607. if (this._updatable) { // update buffer
  29608. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29609. this._data = null;
  29610. }
  29611. };
  29612. Buffer.prototype.dispose = function () {
  29613. if (!this._buffer) {
  29614. return;
  29615. }
  29616. if (this._engine._releaseBuffer(this._buffer)) {
  29617. this._buffer = null;
  29618. }
  29619. };
  29620. return Buffer;
  29621. }());
  29622. BABYLON.Buffer = Buffer;
  29623. })(BABYLON || (BABYLON = {}));
  29624. //# sourceMappingURL=babylon.buffer.js.map
  29625. var BABYLON;
  29626. (function (BABYLON) {
  29627. var VertexBuffer = /** @class */ (function () {
  29628. /**
  29629. * Constructor
  29630. * @param engine the engine
  29631. * @param data the data to use for this vertex buffer
  29632. * @param kind the vertex buffer kind
  29633. * @param updatable whether the data is updatable
  29634. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29635. * @param stride the stride (optional)
  29636. * @param instanced whether the buffer is instanced (optional)
  29637. * @param offset the offset of the data (optional)
  29638. * @param size the number of components (optional)
  29639. * @param type the type of the component (optional)
  29640. * @param normalized whether the data contains normalized data (optional)
  29641. * @param useBytes set to true if stride and offset are in bytes (optional)
  29642. */
  29643. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29644. if (normalized === void 0) { normalized = false; }
  29645. if (useBytes === void 0) { useBytes = false; }
  29646. if (data instanceof BABYLON.Buffer) {
  29647. this._buffer = data;
  29648. this._ownsBuffer = false;
  29649. }
  29650. else {
  29651. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29652. this._ownsBuffer = true;
  29653. }
  29654. this._kind = kind;
  29655. if (type == undefined) {
  29656. var data_1 = this.getData();
  29657. this.type = VertexBuffer.FLOAT;
  29658. if (data_1 instanceof Int8Array)
  29659. this.type = VertexBuffer.BYTE;
  29660. else if (data_1 instanceof Uint8Array)
  29661. this.type = VertexBuffer.UNSIGNED_BYTE;
  29662. else if (data_1 instanceof Int16Array)
  29663. this.type = VertexBuffer.SHORT;
  29664. else if (data_1 instanceof Uint16Array)
  29665. this.type = VertexBuffer.UNSIGNED_SHORT;
  29666. else if (data_1 instanceof Int32Array)
  29667. this.type = VertexBuffer.INT;
  29668. else if (data_1 instanceof Uint32Array)
  29669. this.type = VertexBuffer.UNSIGNED_INT;
  29670. }
  29671. else {
  29672. this.type = type;
  29673. }
  29674. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29675. if (useBytes) {
  29676. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29677. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29678. this.byteOffset = offset || 0;
  29679. }
  29680. else {
  29681. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29682. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29683. this.byteOffset = (offset || 0) * typeByteLength;
  29684. }
  29685. this.normalized = normalized;
  29686. this._instanced = instanced !== undefined ? instanced : false;
  29687. this._instanceDivisor = instanced ? 1 : 0;
  29688. }
  29689. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29690. /**
  29691. * Gets or sets the instance divisor when in instanced mode
  29692. */
  29693. get: function () {
  29694. return this._instanceDivisor;
  29695. },
  29696. set: function (value) {
  29697. this._instanceDivisor = value;
  29698. if (value == 0) {
  29699. this._instanced = false;
  29700. }
  29701. else {
  29702. this._instanced = true;
  29703. }
  29704. },
  29705. enumerable: true,
  29706. configurable: true
  29707. });
  29708. VertexBuffer.prototype._rebuild = function () {
  29709. if (!this._buffer) {
  29710. return;
  29711. }
  29712. this._buffer._rebuild();
  29713. };
  29714. /**
  29715. * Returns the kind of the VertexBuffer (string).
  29716. */
  29717. VertexBuffer.prototype.getKind = function () {
  29718. return this._kind;
  29719. };
  29720. // Properties
  29721. /**
  29722. * Boolean : is the VertexBuffer updatable ?
  29723. */
  29724. VertexBuffer.prototype.isUpdatable = function () {
  29725. return this._buffer.isUpdatable();
  29726. };
  29727. /**
  29728. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29729. */
  29730. VertexBuffer.prototype.getData = function () {
  29731. return this._buffer.getData();
  29732. };
  29733. /**
  29734. * Returns the WebGLBuffer associated to the VertexBuffer.
  29735. */
  29736. VertexBuffer.prototype.getBuffer = function () {
  29737. return this._buffer.getBuffer();
  29738. };
  29739. /**
  29740. * Returns the stride as a multiple of the type byte length.
  29741. * DEPRECATED. Use byteStride instead.
  29742. */
  29743. VertexBuffer.prototype.getStrideSize = function () {
  29744. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29745. };
  29746. /**
  29747. * Returns the offset as a multiple of the type byte length.
  29748. * DEPRECATED. Use byteOffset instead.
  29749. */
  29750. VertexBuffer.prototype.getOffset = function () {
  29751. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29752. };
  29753. /**
  29754. * Returns the number of components per vertex attribute (integer).
  29755. */
  29756. VertexBuffer.prototype.getSize = function () {
  29757. return this._size;
  29758. };
  29759. /**
  29760. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29761. */
  29762. VertexBuffer.prototype.getIsInstanced = function () {
  29763. return this._instanced;
  29764. };
  29765. /**
  29766. * Returns the instancing divisor, zero for non-instanced (integer).
  29767. */
  29768. VertexBuffer.prototype.getInstanceDivisor = function () {
  29769. return this._instanceDivisor;
  29770. };
  29771. // Methods
  29772. /**
  29773. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29774. * Returns the created WebGLBuffer.
  29775. */
  29776. VertexBuffer.prototype.create = function (data) {
  29777. return this._buffer.create(data);
  29778. };
  29779. /**
  29780. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29781. * This function will create a new buffer if the current one is not updatable
  29782. * Returns the updated WebGLBuffer.
  29783. */
  29784. VertexBuffer.prototype.update = function (data) {
  29785. return this._buffer.update(data);
  29786. };
  29787. /**
  29788. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29789. * Returns the directly updated WebGLBuffer.
  29790. * @param data the new data
  29791. * @param offset the new offset
  29792. * @param useBytes set to true if the offset is in bytes
  29793. */
  29794. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29795. if (useBytes === void 0) { useBytes = false; }
  29796. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29797. };
  29798. /**
  29799. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29800. */
  29801. VertexBuffer.prototype.dispose = function () {
  29802. if (this._ownsBuffer) {
  29803. this._buffer.dispose();
  29804. }
  29805. };
  29806. /**
  29807. * Enumerates each value of this vertex buffer as numbers.
  29808. * @param count the number of values to enumerate
  29809. * @param callback the callback function called for each value
  29810. */
  29811. VertexBuffer.prototype.forEach = function (count, callback) {
  29812. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29813. };
  29814. Object.defineProperty(VertexBuffer, "PositionKind", {
  29815. get: function () {
  29816. return VertexBuffer._PositionKind;
  29817. },
  29818. enumerable: true,
  29819. configurable: true
  29820. });
  29821. Object.defineProperty(VertexBuffer, "NormalKind", {
  29822. get: function () {
  29823. return VertexBuffer._NormalKind;
  29824. },
  29825. enumerable: true,
  29826. configurable: true
  29827. });
  29828. Object.defineProperty(VertexBuffer, "TangentKind", {
  29829. get: function () {
  29830. return VertexBuffer._TangentKind;
  29831. },
  29832. enumerable: true,
  29833. configurable: true
  29834. });
  29835. Object.defineProperty(VertexBuffer, "UVKind", {
  29836. get: function () {
  29837. return VertexBuffer._UVKind;
  29838. },
  29839. enumerable: true,
  29840. configurable: true
  29841. });
  29842. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29843. get: function () {
  29844. return VertexBuffer._UV2Kind;
  29845. },
  29846. enumerable: true,
  29847. configurable: true
  29848. });
  29849. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29850. get: function () {
  29851. return VertexBuffer._UV3Kind;
  29852. },
  29853. enumerable: true,
  29854. configurable: true
  29855. });
  29856. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29857. get: function () {
  29858. return VertexBuffer._UV4Kind;
  29859. },
  29860. enumerable: true,
  29861. configurable: true
  29862. });
  29863. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29864. get: function () {
  29865. return VertexBuffer._UV5Kind;
  29866. },
  29867. enumerable: true,
  29868. configurable: true
  29869. });
  29870. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29871. get: function () {
  29872. return VertexBuffer._UV6Kind;
  29873. },
  29874. enumerable: true,
  29875. configurable: true
  29876. });
  29877. Object.defineProperty(VertexBuffer, "ColorKind", {
  29878. get: function () {
  29879. return VertexBuffer._ColorKind;
  29880. },
  29881. enumerable: true,
  29882. configurable: true
  29883. });
  29884. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29885. get: function () {
  29886. return VertexBuffer._MatricesIndicesKind;
  29887. },
  29888. enumerable: true,
  29889. configurable: true
  29890. });
  29891. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29892. get: function () {
  29893. return VertexBuffer._MatricesWeightsKind;
  29894. },
  29895. enumerable: true,
  29896. configurable: true
  29897. });
  29898. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29899. get: function () {
  29900. return VertexBuffer._MatricesIndicesExtraKind;
  29901. },
  29902. enumerable: true,
  29903. configurable: true
  29904. });
  29905. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29906. get: function () {
  29907. return VertexBuffer._MatricesWeightsExtraKind;
  29908. },
  29909. enumerable: true,
  29910. configurable: true
  29911. });
  29912. /**
  29913. * Deduces the stride given a kind.
  29914. * @param kind The kind string to deduce
  29915. * @returns The deduced stride
  29916. */
  29917. VertexBuffer.DeduceStride = function (kind) {
  29918. switch (kind) {
  29919. case VertexBuffer.UVKind:
  29920. case VertexBuffer.UV2Kind:
  29921. case VertexBuffer.UV3Kind:
  29922. case VertexBuffer.UV4Kind:
  29923. case VertexBuffer.UV5Kind:
  29924. case VertexBuffer.UV6Kind:
  29925. return 2;
  29926. case VertexBuffer.NormalKind:
  29927. case VertexBuffer.PositionKind:
  29928. return 3;
  29929. case VertexBuffer.ColorKind:
  29930. case VertexBuffer.MatricesIndicesKind:
  29931. case VertexBuffer.MatricesIndicesExtraKind:
  29932. case VertexBuffer.MatricesWeightsKind:
  29933. case VertexBuffer.MatricesWeightsExtraKind:
  29934. case VertexBuffer.TangentKind:
  29935. return 4;
  29936. default:
  29937. throw new Error("Invalid kind '" + kind + "'");
  29938. }
  29939. };
  29940. /**
  29941. * Gets the byte length of the given type.
  29942. * @param type the type
  29943. * @returns the number of bytes
  29944. */
  29945. VertexBuffer.GetTypeByteLength = function (type) {
  29946. switch (type) {
  29947. case VertexBuffer.BYTE:
  29948. case VertexBuffer.UNSIGNED_BYTE:
  29949. return 1;
  29950. case VertexBuffer.SHORT:
  29951. case VertexBuffer.UNSIGNED_SHORT:
  29952. return 2;
  29953. case VertexBuffer.INT:
  29954. case VertexBuffer.FLOAT:
  29955. return 4;
  29956. default:
  29957. throw new Error("Invalid type '" + type + "'");
  29958. }
  29959. };
  29960. /**
  29961. * Enumerates each value of the given parameters as numbers.
  29962. * @param data the data to enumerate
  29963. * @param byteOffset the byte offset of the data
  29964. * @param byteStride the byte stride of the data
  29965. * @param componentCount the number of components per element
  29966. * @param componentType the type of the component
  29967. * @param count the total number of components
  29968. * @param normalized whether the data is normalized
  29969. * @param callback the callback function called for each value
  29970. */
  29971. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29972. if (data instanceof Array) {
  29973. var offset = byteOffset / 4;
  29974. var stride = byteStride / 4;
  29975. for (var index = 0; index < count; index += componentCount) {
  29976. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29977. callback(data[offset + componentIndex], index + componentIndex);
  29978. }
  29979. offset += stride;
  29980. }
  29981. }
  29982. else {
  29983. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29984. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29985. for (var index = 0; index < count; index += componentCount) {
  29986. var componentByteOffset = byteOffset;
  29987. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29988. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29989. callback(value, index + componentIndex);
  29990. componentByteOffset += componentByteLength;
  29991. }
  29992. byteOffset += byteStride;
  29993. }
  29994. }
  29995. };
  29996. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29997. switch (type) {
  29998. case VertexBuffer.BYTE: {
  29999. var value = dataView.getInt8(byteOffset);
  30000. if (normalized) {
  30001. value = Math.max(value / 127, -1);
  30002. }
  30003. return value;
  30004. }
  30005. case VertexBuffer.UNSIGNED_BYTE: {
  30006. var value = dataView.getUint8(byteOffset);
  30007. if (normalized) {
  30008. value = value / 255;
  30009. }
  30010. return value;
  30011. }
  30012. case VertexBuffer.SHORT: {
  30013. var value = dataView.getInt16(byteOffset, true);
  30014. if (normalized) {
  30015. value = Math.max(value / 16383, -1);
  30016. }
  30017. return value;
  30018. }
  30019. case VertexBuffer.UNSIGNED_SHORT: {
  30020. var value = dataView.getUint16(byteOffset, true);
  30021. if (normalized) {
  30022. value = value / 65535;
  30023. }
  30024. return value;
  30025. }
  30026. case VertexBuffer.FLOAT: {
  30027. return dataView.getFloat32(byteOffset, true);
  30028. }
  30029. default: {
  30030. throw new Error("Invalid component type " + type);
  30031. }
  30032. }
  30033. };
  30034. /**
  30035. * The byte type.
  30036. */
  30037. VertexBuffer.BYTE = 5120;
  30038. /**
  30039. * The unsigned byte type.
  30040. */
  30041. VertexBuffer.UNSIGNED_BYTE = 5121;
  30042. /**
  30043. * The short type.
  30044. */
  30045. VertexBuffer.SHORT = 5122;
  30046. /**
  30047. * The unsigned short type.
  30048. */
  30049. VertexBuffer.UNSIGNED_SHORT = 5123;
  30050. /**
  30051. * The integer type.
  30052. */
  30053. VertexBuffer.INT = 5124;
  30054. /**
  30055. * The unsigned integer type.
  30056. */
  30057. VertexBuffer.UNSIGNED_INT = 5125;
  30058. /**
  30059. * The float type.
  30060. */
  30061. VertexBuffer.FLOAT = 5126;
  30062. // Enums
  30063. VertexBuffer._PositionKind = "position";
  30064. VertexBuffer._NormalKind = "normal";
  30065. VertexBuffer._TangentKind = "tangent";
  30066. VertexBuffer._UVKind = "uv";
  30067. VertexBuffer._UV2Kind = "uv2";
  30068. VertexBuffer._UV3Kind = "uv3";
  30069. VertexBuffer._UV4Kind = "uv4";
  30070. VertexBuffer._UV5Kind = "uv5";
  30071. VertexBuffer._UV6Kind = "uv6";
  30072. VertexBuffer._ColorKind = "color";
  30073. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30074. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30075. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30076. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30077. return VertexBuffer;
  30078. }());
  30079. BABYLON.VertexBuffer = VertexBuffer;
  30080. })(BABYLON || (BABYLON = {}));
  30081. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30082. var BABYLON;
  30083. (function (BABYLON) {
  30084. /**
  30085. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30086. */
  30087. var DummyInternalTextureTracker = /** @class */ (function () {
  30088. function DummyInternalTextureTracker() {
  30089. /**
  30090. * Gets or set the previous tracker in the list
  30091. */
  30092. this.previous = null;
  30093. /**
  30094. * Gets or set the next tracker in the list
  30095. */
  30096. this.next = null;
  30097. }
  30098. return DummyInternalTextureTracker;
  30099. }());
  30100. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30101. })(BABYLON || (BABYLON = {}));
  30102. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30103. var BABYLON;
  30104. (function (BABYLON) {
  30105. /**
  30106. * Class used to store data associated with WebGL texture data for the engine
  30107. * This class should not be used directly
  30108. */
  30109. var InternalTexture = /** @class */ (function () {
  30110. /**
  30111. * Creates a new InternalTexture
  30112. * @param engine defines the engine to use
  30113. * @param dataSource defines the type of data that will be used
  30114. */
  30115. function InternalTexture(engine, dataSource) {
  30116. /**
  30117. * Observable called when the texture is loaded
  30118. */
  30119. this.onLoadedObservable = new BABYLON.Observable();
  30120. /**
  30121. * Gets or set the previous tracker in the list
  30122. */
  30123. this.previous = null;
  30124. /**
  30125. * Gets or set the next tracker in the list
  30126. */
  30127. this.next = null;
  30128. // Private
  30129. /** @hidden */
  30130. this._initialSlot = -1;
  30131. /** @hidden */
  30132. this._designatedSlot = -1;
  30133. /** @hidden */
  30134. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30135. /** @hidden */
  30136. this._comparisonFunction = 0;
  30137. /** @hidden */
  30138. this._lodGenerationScale = 0;
  30139. /** @hidden */
  30140. this._lodGenerationOffset = 0;
  30141. /** @hidden */
  30142. this._isRGBD = false;
  30143. /** @hidden */
  30144. this._references = 1;
  30145. this._engine = engine;
  30146. this._dataSource = dataSource;
  30147. this._webGLTexture = engine._createTexture();
  30148. }
  30149. /**
  30150. * Gets the Engine the texture belongs to.
  30151. * @returns The babylon engine
  30152. */
  30153. InternalTexture.prototype.getEngine = function () {
  30154. return this._engine;
  30155. };
  30156. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30157. /**
  30158. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30159. */
  30160. get: function () {
  30161. return this._dataSource;
  30162. },
  30163. enumerable: true,
  30164. configurable: true
  30165. });
  30166. /**
  30167. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30168. */
  30169. InternalTexture.prototype.incrementReferences = function () {
  30170. this._references++;
  30171. };
  30172. /**
  30173. * Change the size of the texture (not the size of the content)
  30174. * @param width defines the new width
  30175. * @param height defines the new height
  30176. * @param depth defines the new depth (1 by default)
  30177. */
  30178. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30179. if (depth === void 0) { depth = 1; }
  30180. this.width = width;
  30181. this.height = height;
  30182. this.depth = depth;
  30183. this.baseWidth = width;
  30184. this.baseHeight = height;
  30185. this.baseDepth = depth;
  30186. this._size = width * height * depth;
  30187. };
  30188. /** @hidden */
  30189. InternalTexture.prototype._rebuild = function () {
  30190. var _this = this;
  30191. var proxy;
  30192. this.isReady = false;
  30193. this._cachedCoordinatesMode = null;
  30194. this._cachedWrapU = null;
  30195. this._cachedWrapV = null;
  30196. this._cachedAnisotropicFilteringLevel = null;
  30197. switch (this._dataSource) {
  30198. case InternalTexture.DATASOURCE_TEMP:
  30199. return;
  30200. case InternalTexture.DATASOURCE_URL:
  30201. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30202. _this.isReady = true;
  30203. }, null, this._buffer, undefined, this.format);
  30204. proxy._swapAndDie(this);
  30205. return;
  30206. case InternalTexture.DATASOURCE_RAW:
  30207. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30208. proxy._swapAndDie(this);
  30209. this.isReady = true;
  30210. return;
  30211. case InternalTexture.DATASOURCE_RAW3D:
  30212. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30213. proxy._swapAndDie(this);
  30214. this.isReady = true;
  30215. return;
  30216. case InternalTexture.DATASOURCE_DYNAMIC:
  30217. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30218. proxy._swapAndDie(this);
  30219. // The engine will make sure to update content so no need to flag it as isReady = true
  30220. return;
  30221. case InternalTexture.DATASOURCE_RENDERTARGET:
  30222. var options = new BABYLON.RenderTargetCreationOptions();
  30223. options.generateDepthBuffer = this._generateDepthBuffer;
  30224. options.generateMipMaps = this.generateMipMaps;
  30225. options.generateStencilBuffer = this._generateStencilBuffer;
  30226. options.samplingMode = this.samplingMode;
  30227. options.type = this.type;
  30228. if (this.isCube) {
  30229. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30230. }
  30231. else {
  30232. var size = {
  30233. width: this.width,
  30234. height: this.height
  30235. };
  30236. proxy = this._engine.createRenderTargetTexture(size, options);
  30237. }
  30238. proxy._swapAndDie(this);
  30239. this.isReady = true;
  30240. return;
  30241. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30242. var depthTextureOptions = {
  30243. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30244. comparisonFunction: this._comparisonFunction,
  30245. generateStencil: this._generateStencilBuffer,
  30246. isCube: this.isCube
  30247. };
  30248. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30249. proxy._swapAndDie(this);
  30250. this.isReady = true;
  30251. return;
  30252. case InternalTexture.DATASOURCE_CUBE:
  30253. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30254. _this.isReady = true;
  30255. }, null, this.format, this._extension);
  30256. proxy._swapAndDie(this);
  30257. return;
  30258. case InternalTexture.DATASOURCE_CUBERAW:
  30259. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30260. proxy._swapAndDie(this);
  30261. this.isReady = true;
  30262. return;
  30263. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30264. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30265. if (proxy) {
  30266. proxy._swapAndDie(_this);
  30267. }
  30268. _this.isReady = true;
  30269. }, null, this.format, this._extension);
  30270. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30271. return;
  30272. }
  30273. };
  30274. InternalTexture.prototype._swapAndDie = function (target) {
  30275. target._webGLTexture = this._webGLTexture;
  30276. if (this._framebuffer) {
  30277. target._framebuffer = this._framebuffer;
  30278. }
  30279. if (this._depthStencilBuffer) {
  30280. target._depthStencilBuffer = this._depthStencilBuffer;
  30281. }
  30282. if (this._lodTextureHigh) {
  30283. if (target._lodTextureHigh) {
  30284. target._lodTextureHigh.dispose();
  30285. }
  30286. target._lodTextureHigh = this._lodTextureHigh;
  30287. }
  30288. if (this._lodTextureMid) {
  30289. if (target._lodTextureMid) {
  30290. target._lodTextureMid.dispose();
  30291. }
  30292. target._lodTextureMid = this._lodTextureMid;
  30293. }
  30294. if (this._lodTextureLow) {
  30295. if (target._lodTextureLow) {
  30296. target._lodTextureLow.dispose();
  30297. }
  30298. target._lodTextureLow = this._lodTextureLow;
  30299. }
  30300. var cache = this._engine.getLoadedTexturesCache();
  30301. var index = cache.indexOf(this);
  30302. if (index !== -1) {
  30303. cache.splice(index, 1);
  30304. }
  30305. };
  30306. /**
  30307. * Dispose the current allocated resources
  30308. */
  30309. InternalTexture.prototype.dispose = function () {
  30310. if (!this._webGLTexture) {
  30311. return;
  30312. }
  30313. this._references--;
  30314. if (this._references === 0) {
  30315. this._engine._releaseTexture(this);
  30316. this._webGLTexture = null;
  30317. this.previous = null;
  30318. this.next = null;
  30319. }
  30320. };
  30321. /**
  30322. * The source of the texture data is unknown
  30323. */
  30324. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30325. /**
  30326. * Texture data comes from an URL
  30327. */
  30328. InternalTexture.DATASOURCE_URL = 1;
  30329. /**
  30330. * Texture data is only used for temporary storage
  30331. */
  30332. InternalTexture.DATASOURCE_TEMP = 2;
  30333. /**
  30334. * Texture data comes from raw data (ArrayBuffer)
  30335. */
  30336. InternalTexture.DATASOURCE_RAW = 3;
  30337. /**
  30338. * Texture content is dynamic (video or dynamic texture)
  30339. */
  30340. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30341. /**
  30342. * Texture content is generated by rendering to it
  30343. */
  30344. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30345. /**
  30346. * Texture content is part of a multi render target process
  30347. */
  30348. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30349. /**
  30350. * Texture data comes from a cube data file
  30351. */
  30352. InternalTexture.DATASOURCE_CUBE = 7;
  30353. /**
  30354. * Texture data comes from a raw cube data
  30355. */
  30356. InternalTexture.DATASOURCE_CUBERAW = 8;
  30357. /**
  30358. * Texture data come from a prefiltered cube data file
  30359. */
  30360. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30361. /**
  30362. * Texture content is raw 3D data
  30363. */
  30364. InternalTexture.DATASOURCE_RAW3D = 10;
  30365. /**
  30366. * Texture content is a depth texture
  30367. */
  30368. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30369. return InternalTexture;
  30370. }());
  30371. BABYLON.InternalTexture = InternalTexture;
  30372. })(BABYLON || (BABYLON = {}));
  30373. //# sourceMappingURL=babylon.internalTexture.js.map
  30374. var BABYLON;
  30375. (function (BABYLON) {
  30376. var BaseTexture = /** @class */ (function () {
  30377. function BaseTexture(scene) {
  30378. this._hasAlpha = false;
  30379. this.getAlphaFromRGB = false;
  30380. this.level = 1;
  30381. this.coordinatesIndex = 0;
  30382. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30383. /**
  30384. * | Value | Type | Description |
  30385. * | ----- | ------------------ | ----------- |
  30386. * | 0 | CLAMP_ADDRESSMODE | |
  30387. * | 1 | WRAP_ADDRESSMODE | |
  30388. * | 2 | MIRROR_ADDRESSMODE | |
  30389. */
  30390. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30391. /**
  30392. * | Value | Type | Description |
  30393. * | ----- | ------------------ | ----------- |
  30394. * | 0 | CLAMP_ADDRESSMODE | |
  30395. * | 1 | WRAP_ADDRESSMODE | |
  30396. * | 2 | MIRROR_ADDRESSMODE | |
  30397. */
  30398. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30399. /**
  30400. * | Value | Type | Description |
  30401. * | ----- | ------------------ | ----------- |
  30402. * | 0 | CLAMP_ADDRESSMODE | |
  30403. * | 1 | WRAP_ADDRESSMODE | |
  30404. * | 2 | MIRROR_ADDRESSMODE | |
  30405. */
  30406. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30407. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30408. this.isCube = false;
  30409. this.is3D = false;
  30410. this.gammaSpace = true;
  30411. this.invertZ = false;
  30412. this.lodLevelInAlpha = false;
  30413. this.isRenderTarget = false;
  30414. this.animations = new Array();
  30415. /**
  30416. * An event triggered when the texture is disposed.
  30417. */
  30418. this.onDisposeObservable = new BABYLON.Observable();
  30419. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30420. this._cachedSize = BABYLON.Size.Zero();
  30421. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30422. if (this._scene) {
  30423. this._scene.textures.push(this);
  30424. }
  30425. this._uid = null;
  30426. }
  30427. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30428. get: function () {
  30429. return this._hasAlpha;
  30430. },
  30431. set: function (value) {
  30432. if (this._hasAlpha === value) {
  30433. return;
  30434. }
  30435. this._hasAlpha = value;
  30436. if (this._scene) {
  30437. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30438. }
  30439. },
  30440. enumerable: true,
  30441. configurable: true
  30442. });
  30443. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30444. get: function () {
  30445. return this._coordinatesMode;
  30446. },
  30447. /**
  30448. * How a texture is mapped.
  30449. *
  30450. * | Value | Type | Description |
  30451. * | ----- | ----------------------------------- | ----------- |
  30452. * | 0 | EXPLICIT_MODE | |
  30453. * | 1 | SPHERICAL_MODE | |
  30454. * | 2 | PLANAR_MODE | |
  30455. * | 3 | CUBIC_MODE | |
  30456. * | 4 | PROJECTION_MODE | |
  30457. * | 5 | SKYBOX_MODE | |
  30458. * | 6 | INVCUBIC_MODE | |
  30459. * | 7 | EQUIRECTANGULAR_MODE | |
  30460. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30461. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30462. */
  30463. set: function (value) {
  30464. if (this._coordinatesMode === value) {
  30465. return;
  30466. }
  30467. this._coordinatesMode = value;
  30468. if (this._scene) {
  30469. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30470. }
  30471. },
  30472. enumerable: true,
  30473. configurable: true
  30474. });
  30475. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30476. /**
  30477. * Gets whether or not the texture contains RGBD data.
  30478. */
  30479. get: function () {
  30480. return this._texture != null && this._texture._isRGBD;
  30481. },
  30482. enumerable: true,
  30483. configurable: true
  30484. });
  30485. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30486. get: function () {
  30487. if (this._texture)
  30488. return this._texture._lodGenerationOffset;
  30489. return 0.0;
  30490. },
  30491. set: function (value) {
  30492. if (this._texture)
  30493. this._texture._lodGenerationOffset = value;
  30494. },
  30495. enumerable: true,
  30496. configurable: true
  30497. });
  30498. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30499. get: function () {
  30500. if (this._texture)
  30501. return this._texture._lodGenerationScale;
  30502. return 0.0;
  30503. },
  30504. set: function (value) {
  30505. if (this._texture)
  30506. this._texture._lodGenerationScale = value;
  30507. },
  30508. enumerable: true,
  30509. configurable: true
  30510. });
  30511. Object.defineProperty(BaseTexture.prototype, "uid", {
  30512. get: function () {
  30513. if (!this._uid) {
  30514. this._uid = BABYLON.Tools.RandomId();
  30515. }
  30516. return this._uid;
  30517. },
  30518. enumerable: true,
  30519. configurable: true
  30520. });
  30521. BaseTexture.prototype.toString = function () {
  30522. return this.name;
  30523. };
  30524. BaseTexture.prototype.getClassName = function () {
  30525. return "BaseTexture";
  30526. };
  30527. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30528. set: function (callback) {
  30529. if (this._onDisposeObserver) {
  30530. this.onDisposeObservable.remove(this._onDisposeObserver);
  30531. }
  30532. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30533. },
  30534. enumerable: true,
  30535. configurable: true
  30536. });
  30537. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30538. get: function () {
  30539. return true;
  30540. },
  30541. enumerable: true,
  30542. configurable: true
  30543. });
  30544. BaseTexture.prototype.getScene = function () {
  30545. return this._scene;
  30546. };
  30547. BaseTexture.prototype.getTextureMatrix = function () {
  30548. return BABYLON.Matrix.IdentityReadOnly;
  30549. };
  30550. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30551. return BABYLON.Matrix.IdentityReadOnly;
  30552. };
  30553. BaseTexture.prototype.getInternalTexture = function () {
  30554. return this._texture;
  30555. };
  30556. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30557. return !this.isBlocking || this.isReady();
  30558. };
  30559. BaseTexture.prototype.isReady = function () {
  30560. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30561. this.delayLoad();
  30562. return false;
  30563. }
  30564. if (this._texture) {
  30565. return this._texture.isReady;
  30566. }
  30567. return false;
  30568. };
  30569. BaseTexture.prototype.getSize = function () {
  30570. if (this._texture) {
  30571. if (this._texture.width) {
  30572. this._cachedSize.width = this._texture.width;
  30573. this._cachedSize.height = this._texture.height;
  30574. return this._cachedSize;
  30575. }
  30576. if (this._texture._size) {
  30577. this._cachedSize.width = this._texture._size;
  30578. this._cachedSize.height = this._texture._size;
  30579. return this._cachedSize;
  30580. }
  30581. }
  30582. return this._cachedSize;
  30583. };
  30584. BaseTexture.prototype.getBaseSize = function () {
  30585. if (!this.isReady() || !this._texture)
  30586. return BABYLON.Size.Zero();
  30587. if (this._texture._size) {
  30588. return new BABYLON.Size(this._texture._size, this._texture._size);
  30589. }
  30590. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30591. };
  30592. BaseTexture.prototype.scale = function (ratio) {
  30593. };
  30594. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30595. get: function () {
  30596. return false;
  30597. },
  30598. enumerable: true,
  30599. configurable: true
  30600. });
  30601. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30602. if (!this._scene) {
  30603. return null;
  30604. }
  30605. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30606. for (var index = 0; index < texturesCache.length; index++) {
  30607. var texturesCacheEntry = texturesCache[index];
  30608. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30609. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30610. texturesCacheEntry.incrementReferences();
  30611. return texturesCacheEntry;
  30612. }
  30613. }
  30614. }
  30615. return null;
  30616. };
  30617. BaseTexture.prototype._rebuild = function () {
  30618. };
  30619. BaseTexture.prototype.delayLoad = function () {
  30620. };
  30621. BaseTexture.prototype.clone = function () {
  30622. return null;
  30623. };
  30624. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30625. get: function () {
  30626. if (!this._texture) {
  30627. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30628. }
  30629. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30630. },
  30631. enumerable: true,
  30632. configurable: true
  30633. });
  30634. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30635. get: function () {
  30636. if (!this._texture) {
  30637. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30638. }
  30639. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30640. },
  30641. enumerable: true,
  30642. configurable: true
  30643. });
  30644. /**
  30645. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30646. * This will returns an RGBA array buffer containing either in values (0-255) or
  30647. * float values (0-1) depending of the underlying buffer type.
  30648. * @param faceIndex The face of the texture to read (in case of cube texture)
  30649. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30650. * @returns The Array buffer containing the pixels data.
  30651. */
  30652. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30653. if (faceIndex === void 0) { faceIndex = 0; }
  30654. if (level === void 0) { level = 0; }
  30655. if (!this._texture) {
  30656. return null;
  30657. }
  30658. var size = this.getSize();
  30659. var width = size.width;
  30660. var height = size.height;
  30661. var scene = this.getScene();
  30662. if (!scene) {
  30663. return null;
  30664. }
  30665. var engine = scene.getEngine();
  30666. if (level != 0) {
  30667. width = width / Math.pow(2, level);
  30668. height = height / Math.pow(2, level);
  30669. width = Math.round(width);
  30670. height = Math.round(height);
  30671. }
  30672. if (this._texture.isCube) {
  30673. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30674. }
  30675. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30676. };
  30677. BaseTexture.prototype.releaseInternalTexture = function () {
  30678. if (this._texture) {
  30679. this._texture.dispose();
  30680. this._texture = null;
  30681. }
  30682. };
  30683. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30684. get: function () {
  30685. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30686. return null;
  30687. }
  30688. if (!this._texture._sphericalPolynomial) {
  30689. this._texture._sphericalPolynomial =
  30690. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30691. }
  30692. return this._texture._sphericalPolynomial;
  30693. },
  30694. set: function (value) {
  30695. if (this._texture) {
  30696. this._texture._sphericalPolynomial = value;
  30697. }
  30698. },
  30699. enumerable: true,
  30700. configurable: true
  30701. });
  30702. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30703. get: function () {
  30704. if (this._texture) {
  30705. return this._texture._lodTextureHigh;
  30706. }
  30707. return null;
  30708. },
  30709. enumerable: true,
  30710. configurable: true
  30711. });
  30712. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30713. get: function () {
  30714. if (this._texture) {
  30715. return this._texture._lodTextureMid;
  30716. }
  30717. return null;
  30718. },
  30719. enumerable: true,
  30720. configurable: true
  30721. });
  30722. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30723. get: function () {
  30724. if (this._texture) {
  30725. return this._texture._lodTextureLow;
  30726. }
  30727. return null;
  30728. },
  30729. enumerable: true,
  30730. configurable: true
  30731. });
  30732. BaseTexture.prototype.dispose = function () {
  30733. if (!this._scene) {
  30734. return;
  30735. }
  30736. // Animations
  30737. this._scene.stopAnimation(this);
  30738. // Remove from scene
  30739. this._scene._removePendingData(this);
  30740. var index = this._scene.textures.indexOf(this);
  30741. if (index >= 0) {
  30742. this._scene.textures.splice(index, 1);
  30743. }
  30744. if (this._texture === undefined) {
  30745. return;
  30746. }
  30747. // Release
  30748. this.releaseInternalTexture();
  30749. // Callback
  30750. this.onDisposeObservable.notifyObservers(this);
  30751. this.onDisposeObservable.clear();
  30752. };
  30753. BaseTexture.prototype.serialize = function () {
  30754. if (!this.name) {
  30755. return null;
  30756. }
  30757. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30758. // Animations
  30759. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30760. return serializationObject;
  30761. };
  30762. BaseTexture.WhenAllReady = function (textures, callback) {
  30763. var numRemaining = textures.length;
  30764. if (numRemaining === 0) {
  30765. callback();
  30766. return;
  30767. }
  30768. var _loop_1 = function () {
  30769. texture = textures[i];
  30770. if (texture.isReady()) {
  30771. if (--numRemaining === 0) {
  30772. callback();
  30773. }
  30774. }
  30775. else {
  30776. onLoadObservable = texture.onLoadObservable;
  30777. var onLoadCallback_1 = function () {
  30778. onLoadObservable.removeCallback(onLoadCallback_1);
  30779. if (--numRemaining === 0) {
  30780. callback();
  30781. }
  30782. };
  30783. onLoadObservable.add(onLoadCallback_1);
  30784. }
  30785. };
  30786. var texture, onLoadObservable;
  30787. for (var i = 0; i < textures.length; i++) {
  30788. _loop_1();
  30789. }
  30790. };
  30791. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30792. __decorate([
  30793. BABYLON.serialize()
  30794. ], BaseTexture.prototype, "name", void 0);
  30795. __decorate([
  30796. BABYLON.serialize("hasAlpha")
  30797. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30798. __decorate([
  30799. BABYLON.serialize()
  30800. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30801. __decorate([
  30802. BABYLON.serialize()
  30803. ], BaseTexture.prototype, "level", void 0);
  30804. __decorate([
  30805. BABYLON.serialize()
  30806. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30807. __decorate([
  30808. BABYLON.serialize("coordinatesMode")
  30809. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30810. __decorate([
  30811. BABYLON.serialize()
  30812. ], BaseTexture.prototype, "wrapU", void 0);
  30813. __decorate([
  30814. BABYLON.serialize()
  30815. ], BaseTexture.prototype, "wrapV", void 0);
  30816. __decorate([
  30817. BABYLON.serialize()
  30818. ], BaseTexture.prototype, "wrapR", void 0);
  30819. __decorate([
  30820. BABYLON.serialize()
  30821. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30822. __decorate([
  30823. BABYLON.serialize()
  30824. ], BaseTexture.prototype, "isCube", void 0);
  30825. __decorate([
  30826. BABYLON.serialize()
  30827. ], BaseTexture.prototype, "is3D", void 0);
  30828. __decorate([
  30829. BABYLON.serialize()
  30830. ], BaseTexture.prototype, "gammaSpace", void 0);
  30831. __decorate([
  30832. BABYLON.serialize()
  30833. ], BaseTexture.prototype, "invertZ", void 0);
  30834. __decorate([
  30835. BABYLON.serialize()
  30836. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30837. __decorate([
  30838. BABYLON.serialize()
  30839. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30840. __decorate([
  30841. BABYLON.serialize()
  30842. ], BaseTexture.prototype, "lodGenerationScale", null);
  30843. __decorate([
  30844. BABYLON.serialize()
  30845. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30846. return BaseTexture;
  30847. }());
  30848. BABYLON.BaseTexture = BaseTexture;
  30849. })(BABYLON || (BABYLON = {}));
  30850. //# sourceMappingURL=babylon.baseTexture.js.map
  30851. var BABYLON;
  30852. (function (BABYLON) {
  30853. var Texture = /** @class */ (function (_super) {
  30854. __extends(Texture, _super);
  30855. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30856. if (noMipmap === void 0) { noMipmap = false; }
  30857. if (invertY === void 0) { invertY = true; }
  30858. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30859. if (onLoad === void 0) { onLoad = null; }
  30860. if (onError === void 0) { onError = null; }
  30861. if (buffer === void 0) { buffer = null; }
  30862. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30863. var _this = _super.call(this, scene) || this;
  30864. _this.uOffset = 0;
  30865. _this.vOffset = 0;
  30866. _this.uScale = 1.0;
  30867. _this.vScale = 1.0;
  30868. _this.uAng = 0;
  30869. _this.vAng = 0;
  30870. _this.wAng = 0;
  30871. /**
  30872. * Defines the center of rotation (U)
  30873. */
  30874. _this.uRotationCenter = 0.5;
  30875. /**
  30876. * Defines the center of rotation (V)
  30877. */
  30878. _this.vRotationCenter = 0.5;
  30879. /**
  30880. * Defines the center of rotation (W)
  30881. */
  30882. _this.wRotationCenter = 0.5;
  30883. _this._isBlocking = true;
  30884. _this.name = url || "";
  30885. _this.url = url;
  30886. _this._noMipmap = noMipmap;
  30887. _this._invertY = invertY;
  30888. _this._samplingMode = samplingMode;
  30889. _this._buffer = buffer;
  30890. _this._deleteBuffer = deleteBuffer;
  30891. if (format) {
  30892. _this._format = format;
  30893. }
  30894. scene = _this.getScene();
  30895. if (!scene) {
  30896. return _this;
  30897. }
  30898. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30899. var load = function () {
  30900. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30901. _this.onLoadObservable.notifyObservers(_this);
  30902. }
  30903. if (onLoad) {
  30904. onLoad();
  30905. }
  30906. if (!_this.isBlocking && scene) {
  30907. scene.resetCachedMaterial();
  30908. }
  30909. };
  30910. if (!_this.url) {
  30911. _this._delayedOnLoad = load;
  30912. _this._delayedOnError = onError;
  30913. return _this;
  30914. }
  30915. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30916. if (!_this._texture) {
  30917. if (!scene.useDelayedTextureLoading) {
  30918. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30919. if (deleteBuffer) {
  30920. delete _this._buffer;
  30921. }
  30922. }
  30923. else {
  30924. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30925. _this._delayedOnLoad = load;
  30926. _this._delayedOnError = onError;
  30927. }
  30928. }
  30929. else {
  30930. if (_this._texture.isReady) {
  30931. BABYLON.Tools.SetImmediate(function () { return load(); });
  30932. }
  30933. else {
  30934. _this._texture.onLoadedObservable.add(load);
  30935. }
  30936. }
  30937. return _this;
  30938. }
  30939. Object.defineProperty(Texture.prototype, "noMipmap", {
  30940. get: function () {
  30941. return this._noMipmap;
  30942. },
  30943. enumerable: true,
  30944. configurable: true
  30945. });
  30946. Object.defineProperty(Texture.prototype, "isBlocking", {
  30947. get: function () {
  30948. return this._isBlocking;
  30949. },
  30950. set: function (value) {
  30951. this._isBlocking = value;
  30952. },
  30953. enumerable: true,
  30954. configurable: true
  30955. });
  30956. Object.defineProperty(Texture.prototype, "samplingMode", {
  30957. get: function () {
  30958. return this._samplingMode;
  30959. },
  30960. enumerable: true,
  30961. configurable: true
  30962. });
  30963. /**
  30964. * Update the url (and optional buffer) of this texture if url was null during construction.
  30965. * @param url the url of the texture
  30966. * @param buffer the buffer of the texture (defaults to null)
  30967. */
  30968. Texture.prototype.updateURL = function (url, buffer) {
  30969. if (buffer === void 0) { buffer = null; }
  30970. if (this.url) {
  30971. throw new Error("URL is already set");
  30972. }
  30973. this.url = url;
  30974. this._buffer = buffer;
  30975. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30976. this.delayLoad();
  30977. };
  30978. Texture.prototype.delayLoad = function () {
  30979. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30980. return;
  30981. }
  30982. var scene = this.getScene();
  30983. if (!scene) {
  30984. return;
  30985. }
  30986. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30987. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30988. if (!this._texture) {
  30989. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30990. if (this._deleteBuffer) {
  30991. delete this._buffer;
  30992. }
  30993. }
  30994. else {
  30995. if (this._delayedOnLoad) {
  30996. if (this._texture.isReady) {
  30997. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30998. }
  30999. else {
  31000. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31001. }
  31002. }
  31003. }
  31004. this._delayedOnLoad = null;
  31005. this._delayedOnError = null;
  31006. };
  31007. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31008. if (!this._texture) {
  31009. return;
  31010. }
  31011. var scene = this.getScene();
  31012. if (!scene) {
  31013. return;
  31014. }
  31015. this._samplingMode = samplingMode;
  31016. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31017. };
  31018. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31019. x *= this.uScale;
  31020. y *= this.vScale;
  31021. x -= this.uRotationCenter * this.uScale;
  31022. y -= this.vRotationCenter * this.vScale;
  31023. z -= this.wRotationCenter;
  31024. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31025. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31026. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31027. t.z += this.wRotationCenter;
  31028. };
  31029. Texture.prototype.getTextureMatrix = function () {
  31030. var _this = this;
  31031. if (this.uOffset === this._cachedUOffset &&
  31032. this.vOffset === this._cachedVOffset &&
  31033. this.uScale === this._cachedUScale &&
  31034. this.vScale === this._cachedVScale &&
  31035. this.uAng === this._cachedUAng &&
  31036. this.vAng === this._cachedVAng &&
  31037. this.wAng === this._cachedWAng) {
  31038. return this._cachedTextureMatrix;
  31039. }
  31040. this._cachedUOffset = this.uOffset;
  31041. this._cachedVOffset = this.vOffset;
  31042. this._cachedUScale = this.uScale;
  31043. this._cachedVScale = this.vScale;
  31044. this._cachedUAng = this.uAng;
  31045. this._cachedVAng = this.vAng;
  31046. this._cachedWAng = this.wAng;
  31047. if (!this._cachedTextureMatrix) {
  31048. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31049. this._rowGenerationMatrix = new BABYLON.Matrix();
  31050. this._t0 = BABYLON.Vector3.Zero();
  31051. this._t1 = BABYLON.Vector3.Zero();
  31052. this._t2 = BABYLON.Vector3.Zero();
  31053. }
  31054. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31055. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31056. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31057. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31058. this._t1.subtractInPlace(this._t0);
  31059. this._t2.subtractInPlace(this._t0);
  31060. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31061. this._cachedTextureMatrix.m[0] = this._t1.x;
  31062. this._cachedTextureMatrix.m[1] = this._t1.y;
  31063. this._cachedTextureMatrix.m[2] = this._t1.z;
  31064. this._cachedTextureMatrix.m[4] = this._t2.x;
  31065. this._cachedTextureMatrix.m[5] = this._t2.y;
  31066. this._cachedTextureMatrix.m[6] = this._t2.z;
  31067. this._cachedTextureMatrix.m[8] = this._t0.x;
  31068. this._cachedTextureMatrix.m[9] = this._t0.y;
  31069. this._cachedTextureMatrix.m[10] = this._t0.z;
  31070. var scene = this.getScene();
  31071. if (!scene) {
  31072. return this._cachedTextureMatrix;
  31073. }
  31074. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31075. return mat.hasTexture(_this);
  31076. });
  31077. return this._cachedTextureMatrix;
  31078. };
  31079. Texture.prototype.getReflectionTextureMatrix = function () {
  31080. var _this = this;
  31081. var scene = this.getScene();
  31082. if (!scene) {
  31083. return this._cachedTextureMatrix;
  31084. }
  31085. if (this.uOffset === this._cachedUOffset &&
  31086. this.vOffset === this._cachedVOffset &&
  31087. this.uScale === this._cachedUScale &&
  31088. this.vScale === this._cachedVScale &&
  31089. this.coordinatesMode === this._cachedCoordinatesMode) {
  31090. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31091. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31092. return this._cachedTextureMatrix;
  31093. }
  31094. }
  31095. else {
  31096. return this._cachedTextureMatrix;
  31097. }
  31098. }
  31099. if (!this._cachedTextureMatrix) {
  31100. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31101. }
  31102. if (!this._projectionModeMatrix) {
  31103. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31104. }
  31105. this._cachedUOffset = this.uOffset;
  31106. this._cachedVOffset = this.vOffset;
  31107. this._cachedUScale = this.uScale;
  31108. this._cachedVScale = this.vScale;
  31109. this._cachedCoordinatesMode = this.coordinatesMode;
  31110. switch (this.coordinatesMode) {
  31111. case Texture.PLANAR_MODE:
  31112. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31113. this._cachedTextureMatrix[0] = this.uScale;
  31114. this._cachedTextureMatrix[5] = this.vScale;
  31115. this._cachedTextureMatrix[12] = this.uOffset;
  31116. this._cachedTextureMatrix[13] = this.vOffset;
  31117. break;
  31118. case Texture.PROJECTION_MODE:
  31119. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31120. this._projectionModeMatrix.m[0] = 0.5;
  31121. this._projectionModeMatrix.m[5] = -0.5;
  31122. this._projectionModeMatrix.m[10] = 0.0;
  31123. this._projectionModeMatrix.m[12] = 0.5;
  31124. this._projectionModeMatrix.m[13] = 0.5;
  31125. this._projectionModeMatrix.m[14] = 1.0;
  31126. this._projectionModeMatrix.m[15] = 1.0;
  31127. var projectionMatrix = scene.getProjectionMatrix();
  31128. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31129. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31130. break;
  31131. default:
  31132. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31133. break;
  31134. }
  31135. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31136. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31137. });
  31138. return this._cachedTextureMatrix;
  31139. };
  31140. Texture.prototype.clone = function () {
  31141. var _this = this;
  31142. return BABYLON.SerializationHelper.Clone(function () {
  31143. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31144. }, this);
  31145. };
  31146. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31147. get: function () {
  31148. if (!this._onLoadObservable) {
  31149. this._onLoadObservable = new BABYLON.Observable();
  31150. }
  31151. return this._onLoadObservable;
  31152. },
  31153. enumerable: true,
  31154. configurable: true
  31155. });
  31156. Texture.prototype.serialize = function () {
  31157. var serializationObject = _super.prototype.serialize.call(this);
  31158. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31159. serializationObject.base64String = this._buffer;
  31160. serializationObject.name = serializationObject.name.replace("data:", "");
  31161. }
  31162. serializationObject.invertY = this._invertY;
  31163. serializationObject.samplingMode = this.samplingMode;
  31164. return serializationObject;
  31165. };
  31166. Texture.prototype.getClassName = function () {
  31167. return "Texture";
  31168. };
  31169. Texture.prototype.dispose = function () {
  31170. _super.prototype.dispose.call(this);
  31171. if (this._onLoadObservable) {
  31172. this._onLoadObservable.clear();
  31173. this._onLoadObservable = null;
  31174. }
  31175. this._delayedOnLoad = null;
  31176. this._delayedOnError = null;
  31177. };
  31178. // Statics
  31179. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31180. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31181. if (onLoad === void 0) { onLoad = null; }
  31182. if (onError === void 0) { onError = null; }
  31183. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31184. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31185. };
  31186. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31187. if (parsedTexture.customType) {
  31188. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31189. // Update Sampling Mode
  31190. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31191. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31192. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31193. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31194. }
  31195. }
  31196. return parsedCustomTexture;
  31197. }
  31198. if (parsedTexture.isCube) {
  31199. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31200. }
  31201. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31202. return null;
  31203. }
  31204. var texture = BABYLON.SerializationHelper.Parse(function () {
  31205. var generateMipMaps = true;
  31206. if (parsedTexture.noMipmap) {
  31207. generateMipMaps = false;
  31208. }
  31209. if (parsedTexture.mirrorPlane) {
  31210. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31211. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31212. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31213. return mirrorTexture;
  31214. }
  31215. else if (parsedTexture.isRenderTarget) {
  31216. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31217. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31218. return renderTargetTexture;
  31219. }
  31220. else {
  31221. var texture;
  31222. if (parsedTexture.base64String) {
  31223. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31224. }
  31225. else {
  31226. var url = rootUrl + parsedTexture.name;
  31227. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31228. url = parsedTexture.url;
  31229. }
  31230. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31231. }
  31232. return texture;
  31233. }
  31234. }, parsedTexture, scene);
  31235. // Update Sampling Mode
  31236. if (parsedTexture.samplingMode) {
  31237. var sampling = parsedTexture.samplingMode;
  31238. if (texture._samplingMode !== sampling) {
  31239. texture.updateSamplingMode(sampling);
  31240. }
  31241. }
  31242. // Animations
  31243. if (parsedTexture.animations) {
  31244. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31245. var parsedAnimation = parsedTexture.animations[animationIndex];
  31246. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31247. }
  31248. }
  31249. return texture;
  31250. };
  31251. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31252. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31253. if (noMipmap === void 0) { noMipmap = false; }
  31254. if (invertY === void 0) { invertY = true; }
  31255. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31256. if (onLoad === void 0) { onLoad = null; }
  31257. if (onError === void 0) { onError = null; }
  31258. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31259. if (name.substr(0, 5) !== "data:") {
  31260. name = "data:" + name;
  31261. }
  31262. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31263. };
  31264. // Constants
  31265. Texture.NEAREST_SAMPLINGMODE = 1;
  31266. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31267. Texture.BILINEAR_SAMPLINGMODE = 2;
  31268. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31269. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31270. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31271. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31272. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31273. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31274. Texture.NEAREST_LINEAR = 7;
  31275. Texture.NEAREST_NEAREST = 8;
  31276. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31277. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31278. Texture.LINEAR_LINEAR = 11;
  31279. Texture.LINEAR_NEAREST = 12;
  31280. Texture.EXPLICIT_MODE = 0;
  31281. Texture.SPHERICAL_MODE = 1;
  31282. Texture.PLANAR_MODE = 2;
  31283. Texture.CUBIC_MODE = 3;
  31284. Texture.PROJECTION_MODE = 4;
  31285. Texture.SKYBOX_MODE = 5;
  31286. Texture.INVCUBIC_MODE = 6;
  31287. Texture.EQUIRECTANGULAR_MODE = 7;
  31288. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31289. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31290. Texture.CLAMP_ADDRESSMODE = 0;
  31291. Texture.WRAP_ADDRESSMODE = 1;
  31292. Texture.MIRROR_ADDRESSMODE = 2;
  31293. /**
  31294. * 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
  31295. */
  31296. Texture.UseSerializedUrlIfAny = false;
  31297. __decorate([
  31298. BABYLON.serialize()
  31299. ], Texture.prototype, "url", void 0);
  31300. __decorate([
  31301. BABYLON.serialize()
  31302. ], Texture.prototype, "uOffset", void 0);
  31303. __decorate([
  31304. BABYLON.serialize()
  31305. ], Texture.prototype, "vOffset", void 0);
  31306. __decorate([
  31307. BABYLON.serialize()
  31308. ], Texture.prototype, "uScale", void 0);
  31309. __decorate([
  31310. BABYLON.serialize()
  31311. ], Texture.prototype, "vScale", void 0);
  31312. __decorate([
  31313. BABYLON.serialize()
  31314. ], Texture.prototype, "uAng", void 0);
  31315. __decorate([
  31316. BABYLON.serialize()
  31317. ], Texture.prototype, "vAng", void 0);
  31318. __decorate([
  31319. BABYLON.serialize()
  31320. ], Texture.prototype, "wAng", void 0);
  31321. __decorate([
  31322. BABYLON.serialize()
  31323. ], Texture.prototype, "uRotationCenter", void 0);
  31324. __decorate([
  31325. BABYLON.serialize()
  31326. ], Texture.prototype, "vRotationCenter", void 0);
  31327. __decorate([
  31328. BABYLON.serialize()
  31329. ], Texture.prototype, "wRotationCenter", void 0);
  31330. __decorate([
  31331. BABYLON.serialize()
  31332. ], Texture.prototype, "isBlocking", null);
  31333. return Texture;
  31334. }(BABYLON.BaseTexture));
  31335. BABYLON.Texture = Texture;
  31336. })(BABYLON || (BABYLON = {}));
  31337. //# sourceMappingURL=babylon.texture.js.map
  31338. var BABYLON;
  31339. (function (BABYLON) {
  31340. /**
  31341. * @hidden
  31342. **/
  31343. var _InstancesBatch = /** @class */ (function () {
  31344. function _InstancesBatch() {
  31345. this.mustReturn = false;
  31346. this.visibleInstances = new Array();
  31347. this.renderSelf = new Array();
  31348. }
  31349. return _InstancesBatch;
  31350. }());
  31351. BABYLON._InstancesBatch = _InstancesBatch;
  31352. var Mesh = /** @class */ (function (_super) {
  31353. __extends(Mesh, _super);
  31354. /**
  31355. * @constructor
  31356. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31357. * @param {Scene} scene The scene to add this mesh to.
  31358. * @param {Node} parent The parent of this mesh, if it has one
  31359. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31360. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31361. * When false, achieved by calling a clone(), also passing False.
  31362. * This will make creation of children, recursive.
  31363. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31364. */
  31365. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31366. if (scene === void 0) { scene = null; }
  31367. if (parent === void 0) { parent = null; }
  31368. if (source === void 0) { source = null; }
  31369. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31370. var _this = _super.call(this, name, scene) || this;
  31371. // Events
  31372. /**
  31373. * An event triggered before rendering the mesh
  31374. */
  31375. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31376. /**
  31377. * An event triggered after rendering the mesh
  31378. */
  31379. _this.onAfterRenderObservable = new BABYLON.Observable();
  31380. /**
  31381. * An event triggered before drawing the mesh
  31382. */
  31383. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31384. // Members
  31385. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31386. _this.instances = new Array();
  31387. _this._LODLevels = new Array();
  31388. _this._visibleInstances = {};
  31389. _this._renderIdForInstances = new Array();
  31390. _this._batchCache = new _InstancesBatch();
  31391. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31392. // Use by builder only to know what orientation were the mesh build in.
  31393. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31394. _this.overrideMaterialSideOrientation = null;
  31395. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31396. // Will be used to save a source mesh reference, If any
  31397. _this._source = null;
  31398. scene = _this.getScene();
  31399. if (source) {
  31400. // Geometry
  31401. if (source._geometry) {
  31402. source._geometry.applyToMesh(_this);
  31403. }
  31404. // Deep copy
  31405. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31406. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31407. // Source mesh
  31408. _this._source = source;
  31409. // Metadata
  31410. if (source.metadata && source.metadata.clone) {
  31411. _this.metadata = source.metadata.clone();
  31412. }
  31413. else {
  31414. _this.metadata = source.metadata;
  31415. }
  31416. // Tags
  31417. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31418. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31419. }
  31420. // Parent
  31421. _this.parent = source.parent;
  31422. // Pivot
  31423. _this.setPivotMatrix(source.getPivotMatrix());
  31424. _this.id = name + "." + source.id;
  31425. // Material
  31426. _this.material = source.material;
  31427. var index;
  31428. if (!doNotCloneChildren) {
  31429. // Children
  31430. var directDescendants = source.getDescendants(true);
  31431. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31432. var child = directDescendants[index_1];
  31433. if (child.clone) {
  31434. child.clone(name + "." + child.name, _this);
  31435. }
  31436. }
  31437. }
  31438. // Physics clone
  31439. var physicsEngine = _this.getScene().getPhysicsEngine();
  31440. if (clonePhysicsImpostor && physicsEngine) {
  31441. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31442. if (impostor) {
  31443. _this.physicsImpostor = impostor.clone(_this);
  31444. }
  31445. }
  31446. // Particles
  31447. for (index = 0; index < scene.particleSystems.length; index++) {
  31448. var system = scene.particleSystems[index];
  31449. if (system.emitter === source) {
  31450. system.clone(system.name, _this);
  31451. }
  31452. }
  31453. _this.refreshBoundingInfo();
  31454. _this.computeWorldMatrix(true);
  31455. }
  31456. // Parent
  31457. if (parent !== null) {
  31458. _this.parent = parent;
  31459. }
  31460. return _this;
  31461. }
  31462. Object.defineProperty(Mesh, "FRONTSIDE", {
  31463. /**
  31464. * Mesh side orientation : usually the external or front surface
  31465. */
  31466. get: function () {
  31467. return Mesh._FRONTSIDE;
  31468. },
  31469. enumerable: true,
  31470. configurable: true
  31471. });
  31472. Object.defineProperty(Mesh, "BACKSIDE", {
  31473. /**
  31474. * Mesh side orientation : usually the internal or back surface
  31475. */
  31476. get: function () {
  31477. return Mesh._BACKSIDE;
  31478. },
  31479. enumerable: true,
  31480. configurable: true
  31481. });
  31482. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31483. /**
  31484. * Mesh side orientation : both internal and external or front and back surfaces
  31485. */
  31486. get: function () {
  31487. return Mesh._DOUBLESIDE;
  31488. },
  31489. enumerable: true,
  31490. configurable: true
  31491. });
  31492. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31493. /**
  31494. * Mesh side orientation : by default, `FRONTSIDE`
  31495. */
  31496. get: function () {
  31497. return Mesh._DEFAULTSIDE;
  31498. },
  31499. enumerable: true,
  31500. configurable: true
  31501. });
  31502. Object.defineProperty(Mesh, "NO_CAP", {
  31503. /**
  31504. * Mesh cap setting : no cap
  31505. */
  31506. get: function () {
  31507. return Mesh._NO_CAP;
  31508. },
  31509. enumerable: true,
  31510. configurable: true
  31511. });
  31512. Object.defineProperty(Mesh, "CAP_START", {
  31513. /**
  31514. * Mesh cap setting : one cap at the beginning of the mesh
  31515. */
  31516. get: function () {
  31517. return Mesh._CAP_START;
  31518. },
  31519. enumerable: true,
  31520. configurable: true
  31521. });
  31522. Object.defineProperty(Mesh, "CAP_END", {
  31523. /**
  31524. * Mesh cap setting : one cap at the end of the mesh
  31525. */
  31526. get: function () {
  31527. return Mesh._CAP_END;
  31528. },
  31529. enumerable: true,
  31530. configurable: true
  31531. });
  31532. Object.defineProperty(Mesh, "CAP_ALL", {
  31533. /**
  31534. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31535. */
  31536. get: function () {
  31537. return Mesh._CAP_ALL;
  31538. },
  31539. enumerable: true,
  31540. configurable: true
  31541. });
  31542. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31543. set: function (callback) {
  31544. if (this._onBeforeDrawObserver) {
  31545. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31546. }
  31547. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31548. },
  31549. enumerable: true,
  31550. configurable: true
  31551. });
  31552. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31553. get: function () {
  31554. return this._morphTargetManager;
  31555. },
  31556. set: function (value) {
  31557. if (this._morphTargetManager === value) {
  31558. return;
  31559. }
  31560. this._morphTargetManager = value;
  31561. this._syncGeometryWithMorphTargetManager();
  31562. },
  31563. enumerable: true,
  31564. configurable: true
  31565. });
  31566. Object.defineProperty(Mesh.prototype, "source", {
  31567. get: function () {
  31568. return this._source;
  31569. },
  31570. enumerable: true,
  31571. configurable: true
  31572. });
  31573. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31574. get: function () {
  31575. return this._unIndexed;
  31576. },
  31577. set: function (value) {
  31578. if (this._unIndexed !== value) {
  31579. this._unIndexed = value;
  31580. this._markSubMeshesAsAttributesDirty();
  31581. }
  31582. },
  31583. enumerable: true,
  31584. configurable: true
  31585. });
  31586. // Methods
  31587. /**
  31588. * Returns the string "Mesh".
  31589. */
  31590. Mesh.prototype.getClassName = function () {
  31591. return "Mesh";
  31592. };
  31593. /**
  31594. * Returns a string.
  31595. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31596. */
  31597. Mesh.prototype.toString = function (fullDetails) {
  31598. var ret = _super.prototype.toString.call(this, fullDetails);
  31599. ret += ", n vertices: " + this.getTotalVertices();
  31600. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31601. if (this.animations) {
  31602. for (var i = 0; i < this.animations.length; i++) {
  31603. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31604. }
  31605. }
  31606. if (fullDetails) {
  31607. if (this._geometry) {
  31608. var ib = this.getIndices();
  31609. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31610. if (vb && ib) {
  31611. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31612. }
  31613. }
  31614. else {
  31615. ret += ", flat shading: UNKNOWN";
  31616. }
  31617. }
  31618. return ret;
  31619. };
  31620. Mesh.prototype._unBindEffect = function () {
  31621. _super.prototype._unBindEffect.call(this);
  31622. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31623. var instance = _a[_i];
  31624. instance._unBindEffect();
  31625. }
  31626. };
  31627. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31628. /**
  31629. * True if the mesh has some Levels Of Details (LOD).
  31630. * Returns a boolean.
  31631. */
  31632. get: function () {
  31633. return this._LODLevels.length > 0;
  31634. },
  31635. enumerable: true,
  31636. configurable: true
  31637. });
  31638. /**
  31639. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31640. * @returns an array of {BABYLON.MeshLODLevel}
  31641. */
  31642. Mesh.prototype.getLODLevels = function () {
  31643. return this._LODLevels;
  31644. };
  31645. Mesh.prototype._sortLODLevels = function () {
  31646. this._LODLevels.sort(function (a, b) {
  31647. if (a.distance < b.distance) {
  31648. return 1;
  31649. }
  31650. if (a.distance > b.distance) {
  31651. return -1;
  31652. }
  31653. return 0;
  31654. });
  31655. };
  31656. /**
  31657. * Add a mesh as LOD level triggered at the given distance.
  31658. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31659. * @param distance The distance from the center of the object to show this level
  31660. * @param mesh The mesh to be added as LOD level (can be null)
  31661. * @return This mesh (for chaining)
  31662. */
  31663. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31664. if (mesh && mesh._masterMesh) {
  31665. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31666. return this;
  31667. }
  31668. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31669. this._LODLevels.push(level);
  31670. if (mesh) {
  31671. mesh._masterMesh = this;
  31672. }
  31673. this._sortLODLevels();
  31674. return this;
  31675. };
  31676. /**
  31677. * Returns the LOD level mesh at the passed distance or null if not found.
  31678. * It is related to the method `addLODLevel(distance, mesh)`.
  31679. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31680. * Returns an object Mesh or `null`.
  31681. */
  31682. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31683. for (var index = 0; index < this._LODLevels.length; index++) {
  31684. var level = this._LODLevels[index];
  31685. if (level.distance === distance) {
  31686. return level.mesh;
  31687. }
  31688. }
  31689. return null;
  31690. };
  31691. /**
  31692. * Remove a mesh from the LOD array
  31693. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31694. * @param {Mesh} mesh The mesh to be removed.
  31695. * @return {Mesh} This mesh (for chaining)
  31696. */
  31697. Mesh.prototype.removeLODLevel = function (mesh) {
  31698. for (var index = 0; index < this._LODLevels.length; index++) {
  31699. if (this._LODLevels[index].mesh === mesh) {
  31700. this._LODLevels.splice(index, 1);
  31701. if (mesh) {
  31702. mesh._masterMesh = null;
  31703. }
  31704. }
  31705. }
  31706. this._sortLODLevels();
  31707. return this;
  31708. };
  31709. /**
  31710. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31711. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31712. */
  31713. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31714. if (!this._LODLevels || this._LODLevels.length === 0) {
  31715. return this;
  31716. }
  31717. var bSphere;
  31718. if (boundingSphere) {
  31719. bSphere = boundingSphere;
  31720. }
  31721. else {
  31722. var boundingInfo = this.getBoundingInfo();
  31723. bSphere = boundingInfo.boundingSphere;
  31724. }
  31725. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31726. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31727. if (this.onLODLevelSelection) {
  31728. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31729. }
  31730. return this;
  31731. }
  31732. for (var index = 0; index < this._LODLevels.length; index++) {
  31733. var level = this._LODLevels[index];
  31734. if (level.distance < distanceToCamera) {
  31735. if (level.mesh) {
  31736. level.mesh._preActivate();
  31737. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31738. }
  31739. if (this.onLODLevelSelection) {
  31740. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31741. }
  31742. return level.mesh;
  31743. }
  31744. }
  31745. if (this.onLODLevelSelection) {
  31746. this.onLODLevelSelection(distanceToCamera, this, this);
  31747. }
  31748. return this;
  31749. };
  31750. Object.defineProperty(Mesh.prototype, "geometry", {
  31751. /**
  31752. * Returns the mesh internal Geometry object.
  31753. */
  31754. get: function () {
  31755. return this._geometry;
  31756. },
  31757. enumerable: true,
  31758. configurable: true
  31759. });
  31760. /**
  31761. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31762. */
  31763. Mesh.prototype.getTotalVertices = function () {
  31764. if (this._geometry === null || this._geometry === undefined) {
  31765. return 0;
  31766. }
  31767. return this._geometry.getTotalVertices();
  31768. };
  31769. /**
  31770. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31771. * 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.
  31772. * You can force the copy with forceCopy === true
  31773. * Returns null if the mesh has no geometry or no vertex buffer.
  31774. * Possible `kind` values :
  31775. * - BABYLON.VertexBuffer.PositionKind
  31776. * - BABYLON.VertexBuffer.UVKind
  31777. * - BABYLON.VertexBuffer.UV2Kind
  31778. * - BABYLON.VertexBuffer.UV3Kind
  31779. * - BABYLON.VertexBuffer.UV4Kind
  31780. * - BABYLON.VertexBuffer.UV5Kind
  31781. * - BABYLON.VertexBuffer.UV6Kind
  31782. * - BABYLON.VertexBuffer.ColorKind
  31783. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31784. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31785. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31786. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31787. */
  31788. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31789. if (!this._geometry) {
  31790. return null;
  31791. }
  31792. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31793. };
  31794. /**
  31795. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31796. * Returns `null` if the mesh has no geometry.
  31797. * Possible `kind` values :
  31798. * - BABYLON.VertexBuffer.PositionKind
  31799. * - BABYLON.VertexBuffer.UVKind
  31800. * - BABYLON.VertexBuffer.UV2Kind
  31801. * - BABYLON.VertexBuffer.UV3Kind
  31802. * - BABYLON.VertexBuffer.UV4Kind
  31803. * - BABYLON.VertexBuffer.UV5Kind
  31804. * - BABYLON.VertexBuffer.UV6Kind
  31805. * - BABYLON.VertexBuffer.ColorKind
  31806. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31807. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31808. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31809. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31810. */
  31811. Mesh.prototype.getVertexBuffer = function (kind) {
  31812. if (!this._geometry) {
  31813. return null;
  31814. }
  31815. return this._geometry.getVertexBuffer(kind);
  31816. };
  31817. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31818. if (!this._geometry) {
  31819. if (this._delayInfo) {
  31820. return this._delayInfo.indexOf(kind) !== -1;
  31821. }
  31822. return false;
  31823. }
  31824. return this._geometry.isVerticesDataPresent(kind);
  31825. };
  31826. /**
  31827. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31828. * Possible `kind` values :
  31829. * - BABYLON.VertexBuffer.PositionKind
  31830. * - BABYLON.VertexBuffer.UVKind
  31831. * - BABYLON.VertexBuffer.UV2Kind
  31832. * - BABYLON.VertexBuffer.UV3Kind
  31833. * - BABYLON.VertexBuffer.UV4Kind
  31834. * - BABYLON.VertexBuffer.UV5Kind
  31835. * - BABYLON.VertexBuffer.UV6Kind
  31836. * - BABYLON.VertexBuffer.ColorKind
  31837. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31838. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31839. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31840. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31841. */
  31842. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31843. if (!this._geometry) {
  31844. if (this._delayInfo) {
  31845. return this._delayInfo.indexOf(kind) !== -1;
  31846. }
  31847. return false;
  31848. }
  31849. return this._geometry.isVertexBufferUpdatable(kind);
  31850. };
  31851. /**
  31852. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31853. * Possible `kind` values :
  31854. * - BABYLON.VertexBuffer.PositionKind
  31855. * - BABYLON.VertexBuffer.UVKind
  31856. * - BABYLON.VertexBuffer.UV2Kind
  31857. * - BABYLON.VertexBuffer.UV3Kind
  31858. * - BABYLON.VertexBuffer.UV4Kind
  31859. * - BABYLON.VertexBuffer.UV5Kind
  31860. * - BABYLON.VertexBuffer.UV6Kind
  31861. * - BABYLON.VertexBuffer.ColorKind
  31862. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31863. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31864. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31865. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31866. */
  31867. Mesh.prototype.getVerticesDataKinds = function () {
  31868. if (!this._geometry) {
  31869. var result = new Array();
  31870. if (this._delayInfo) {
  31871. this._delayInfo.forEach(function (kind, index, array) {
  31872. result.push(kind);
  31873. });
  31874. }
  31875. return result;
  31876. }
  31877. return this._geometry.getVerticesDataKinds();
  31878. };
  31879. /**
  31880. * Returns a positive integer : the total number of indices in this mesh geometry.
  31881. * Returns zero if the mesh has no geometry.
  31882. */
  31883. Mesh.prototype.getTotalIndices = function () {
  31884. if (!this._geometry) {
  31885. return 0;
  31886. }
  31887. return this._geometry.getTotalIndices();
  31888. };
  31889. /**
  31890. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31891. * 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.
  31892. * Returns an empty array if the mesh has no geometry.
  31893. */
  31894. Mesh.prototype.getIndices = function (copyWhenShared) {
  31895. if (!this._geometry) {
  31896. return [];
  31897. }
  31898. return this._geometry.getIndices(copyWhenShared);
  31899. };
  31900. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31901. get: function () {
  31902. return this._masterMesh !== null && this._masterMesh !== undefined;
  31903. },
  31904. enumerable: true,
  31905. configurable: true
  31906. });
  31907. /**
  31908. * Determine if the current mesh is ready to be rendered
  31909. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31910. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31911. * @returns true if all associated assets are ready (material, textures, shaders)
  31912. */
  31913. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31914. if (completeCheck === void 0) { completeCheck = false; }
  31915. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31916. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31917. return false;
  31918. }
  31919. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31920. return false;
  31921. }
  31922. if (!this.subMeshes || this.subMeshes.length === 0) {
  31923. return true;
  31924. }
  31925. if (!completeCheck) {
  31926. return true;
  31927. }
  31928. var engine = this.getEngine();
  31929. var scene = this.getScene();
  31930. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31931. this.computeWorldMatrix();
  31932. var mat = this.material || scene.defaultMaterial;
  31933. if (mat) {
  31934. if (mat.storeEffectOnSubMeshes) {
  31935. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31936. var subMesh = _a[_i];
  31937. var effectiveMaterial = subMesh.getMaterial();
  31938. if (effectiveMaterial) {
  31939. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31940. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31941. return false;
  31942. }
  31943. }
  31944. else {
  31945. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31946. return false;
  31947. }
  31948. }
  31949. }
  31950. }
  31951. }
  31952. else {
  31953. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31954. return false;
  31955. }
  31956. }
  31957. }
  31958. // Shadows
  31959. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31960. var light = _c[_b];
  31961. var generator = light.getShadowGenerator();
  31962. if (generator) {
  31963. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31964. var subMesh = _e[_d];
  31965. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31966. return false;
  31967. }
  31968. }
  31969. }
  31970. }
  31971. // LOD
  31972. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31973. var lod = _g[_f];
  31974. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31975. return false;
  31976. }
  31977. }
  31978. return true;
  31979. };
  31980. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31981. /**
  31982. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31983. * This property is pertinent only for updatable parametric shapes.
  31984. */
  31985. get: function () {
  31986. return this._areNormalsFrozen;
  31987. },
  31988. enumerable: true,
  31989. configurable: true
  31990. });
  31991. /**
  31992. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31993. * It has no effect at all on other shapes.
  31994. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31995. * Returns the Mesh.
  31996. */
  31997. Mesh.prototype.freezeNormals = function () {
  31998. this._areNormalsFrozen = true;
  31999. return this;
  32000. };
  32001. /**
  32002. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32003. * It has no effect at all on other shapes.
  32004. * It reactivates the mesh normals computation if it was previously frozen.
  32005. * Returns the Mesh.
  32006. */
  32007. Mesh.prototype.unfreezeNormals = function () {
  32008. this._areNormalsFrozen = false;
  32009. return this;
  32010. };
  32011. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32012. /**
  32013. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32014. */
  32015. set: function (count) {
  32016. this._overridenInstanceCount = count;
  32017. },
  32018. enumerable: true,
  32019. configurable: true
  32020. });
  32021. // Methods
  32022. Mesh.prototype._preActivate = function () {
  32023. var sceneRenderId = this.getScene().getRenderId();
  32024. if (this._preActivateId === sceneRenderId) {
  32025. return this;
  32026. }
  32027. this._preActivateId = sceneRenderId;
  32028. this._visibleInstances = null;
  32029. return this;
  32030. };
  32031. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32032. if (this._visibleInstances) {
  32033. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32034. }
  32035. return this;
  32036. };
  32037. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32038. if (!this._visibleInstances) {
  32039. this._visibleInstances = {};
  32040. this._visibleInstances.defaultRenderId = renderId;
  32041. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32042. }
  32043. if (!this._visibleInstances[renderId]) {
  32044. this._visibleInstances[renderId] = new Array();
  32045. }
  32046. this._visibleInstances[renderId].push(instance);
  32047. return this;
  32048. };
  32049. /**
  32050. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32051. * This means the mesh underlying bounding box and sphere are recomputed.
  32052. * Returns the Mesh.
  32053. */
  32054. Mesh.prototype.refreshBoundingInfo = function () {
  32055. return this._refreshBoundingInfo(false);
  32056. };
  32057. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32058. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32059. return this;
  32060. }
  32061. var data = this._getPositionData(applySkeleton);
  32062. if (data) {
  32063. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32064. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32065. }
  32066. if (this.subMeshes) {
  32067. for (var index = 0; index < this.subMeshes.length; index++) {
  32068. this.subMeshes[index].refreshBoundingInfo();
  32069. }
  32070. }
  32071. this._updateBoundingInfo();
  32072. return this;
  32073. };
  32074. Mesh.prototype._getPositionData = function (applySkeleton) {
  32075. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32076. if (data && applySkeleton && this.skeleton) {
  32077. data = BABYLON.Tools.Slice(data);
  32078. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32079. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32080. if (matricesWeightsData && matricesIndicesData) {
  32081. var needExtras = this.numBoneInfluencers > 4;
  32082. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32083. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32084. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32085. var tempVector = BABYLON.Tmp.Vector3[0];
  32086. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32087. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32088. var matWeightIdx = 0;
  32089. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32090. finalMatrix.reset();
  32091. var inf;
  32092. var weight;
  32093. for (inf = 0; inf < 4; inf++) {
  32094. weight = matricesWeightsData[matWeightIdx + inf];
  32095. if (weight <= 0)
  32096. break;
  32097. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32098. finalMatrix.addToSelf(tempMatrix);
  32099. }
  32100. if (needExtras) {
  32101. for (inf = 0; inf < 4; inf++) {
  32102. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32103. if (weight <= 0)
  32104. break;
  32105. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32106. finalMatrix.addToSelf(tempMatrix);
  32107. }
  32108. }
  32109. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32110. tempVector.toArray(data, index);
  32111. }
  32112. }
  32113. }
  32114. return data;
  32115. };
  32116. Mesh.prototype._createGlobalSubMesh = function (force) {
  32117. var totalVertices = this.getTotalVertices();
  32118. if (!totalVertices || !this.getIndices()) {
  32119. return null;
  32120. }
  32121. // Check if we need to recreate the submeshes
  32122. if (this.subMeshes && this.subMeshes.length > 0) {
  32123. var ib = this.getIndices();
  32124. if (!ib) {
  32125. return null;
  32126. }
  32127. var totalIndices = ib.length;
  32128. var needToRecreate = false;
  32129. if (force) {
  32130. needToRecreate = true;
  32131. }
  32132. else {
  32133. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32134. var submesh = _a[_i];
  32135. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32136. needToRecreate = true;
  32137. break;
  32138. }
  32139. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32140. needToRecreate = true;
  32141. break;
  32142. }
  32143. }
  32144. }
  32145. if (!needToRecreate) {
  32146. return this.subMeshes[0];
  32147. }
  32148. }
  32149. this.releaseSubMeshes();
  32150. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32151. };
  32152. Mesh.prototype.subdivide = function (count) {
  32153. if (count < 1) {
  32154. return;
  32155. }
  32156. var totalIndices = this.getTotalIndices();
  32157. var subdivisionSize = (totalIndices / count) | 0;
  32158. var offset = 0;
  32159. // Ensure that subdivisionSize is a multiple of 3
  32160. while (subdivisionSize % 3 !== 0) {
  32161. subdivisionSize++;
  32162. }
  32163. this.releaseSubMeshes();
  32164. for (var index = 0; index < count; index++) {
  32165. if (offset >= totalIndices) {
  32166. break;
  32167. }
  32168. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32169. offset += subdivisionSize;
  32170. }
  32171. this.synchronizeInstances();
  32172. };
  32173. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32174. if (updatable === void 0) { updatable = false; }
  32175. if (!this._geometry) {
  32176. var vertexData = new BABYLON.VertexData();
  32177. vertexData.set(data, kind);
  32178. var scene = this.getScene();
  32179. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32180. }
  32181. else {
  32182. this._geometry.setVerticesData(kind, data, updatable, stride);
  32183. }
  32184. return this;
  32185. };
  32186. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32187. if (updatable === void 0) { updatable = true; }
  32188. var vb = this.getVertexBuffer(kind);
  32189. if (!vb || vb.isUpdatable() === updatable) {
  32190. return;
  32191. }
  32192. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32193. };
  32194. /**
  32195. * Sets the mesh VertexBuffer.
  32196. * Returns the Mesh.
  32197. */
  32198. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32199. if (!this._geometry) {
  32200. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32201. }
  32202. this._geometry.setVerticesBuffer(buffer);
  32203. return this;
  32204. };
  32205. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32206. if (!this._geometry) {
  32207. return this;
  32208. }
  32209. if (!makeItUnique) {
  32210. this._geometry.updateVerticesData(kind, data, updateExtends);
  32211. }
  32212. else {
  32213. this.makeGeometryUnique();
  32214. this.updateVerticesData(kind, data, updateExtends, false);
  32215. }
  32216. return this;
  32217. };
  32218. /**
  32219. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32220. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32221. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32222. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32223. * Returns the Mesh.
  32224. */
  32225. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32226. if (computeNormals === void 0) { computeNormals = true; }
  32227. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32228. if (!positions) {
  32229. return this;
  32230. }
  32231. positionFunction(positions);
  32232. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32233. if (computeNormals) {
  32234. var indices = this.getIndices();
  32235. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32236. if (!normals) {
  32237. return this;
  32238. }
  32239. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32240. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32241. }
  32242. return this;
  32243. };
  32244. /**
  32245. * Creates a un-shared specific occurence of the geometry for the mesh.
  32246. * Returns the Mesh.
  32247. */
  32248. Mesh.prototype.makeGeometryUnique = function () {
  32249. if (!this._geometry) {
  32250. return this;
  32251. }
  32252. var oldGeometry = this._geometry;
  32253. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32254. oldGeometry.releaseForMesh(this, true);
  32255. geometry.applyToMesh(this);
  32256. return this;
  32257. };
  32258. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32259. if (totalVertices === void 0) { totalVertices = null; }
  32260. if (updatable === void 0) { updatable = false; }
  32261. if (!this._geometry) {
  32262. var vertexData = new BABYLON.VertexData();
  32263. vertexData.indices = indices;
  32264. var scene = this.getScene();
  32265. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32266. }
  32267. else {
  32268. this._geometry.setIndices(indices, totalVertices, updatable);
  32269. }
  32270. return this;
  32271. };
  32272. /**
  32273. * Update the current index buffer
  32274. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32275. * Returns the Mesh.
  32276. */
  32277. Mesh.prototype.updateIndices = function (indices, offset) {
  32278. if (!this._geometry) {
  32279. return this;
  32280. }
  32281. this._geometry.updateIndices(indices, offset);
  32282. return this;
  32283. };
  32284. /**
  32285. * Invert the geometry to move from a right handed system to a left handed one.
  32286. * Returns the Mesh.
  32287. */
  32288. Mesh.prototype.toLeftHanded = function () {
  32289. if (!this._geometry) {
  32290. return this;
  32291. }
  32292. this._geometry.toLeftHanded();
  32293. return this;
  32294. };
  32295. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32296. if (!this._geometry) {
  32297. return this;
  32298. }
  32299. var engine = this.getScene().getEngine();
  32300. // Wireframe
  32301. var indexToBind;
  32302. if (this._unIndexed) {
  32303. indexToBind = null;
  32304. }
  32305. else {
  32306. switch (fillMode) {
  32307. case BABYLON.Material.PointFillMode:
  32308. indexToBind = null;
  32309. break;
  32310. case BABYLON.Material.WireFrameFillMode:
  32311. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32312. break;
  32313. default:
  32314. case BABYLON.Material.TriangleFillMode:
  32315. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32316. break;
  32317. }
  32318. }
  32319. // VBOs
  32320. this._geometry._bind(effect, indexToBind);
  32321. return this;
  32322. };
  32323. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32324. if (alternate === void 0) { alternate = false; }
  32325. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32326. return this;
  32327. }
  32328. this.onBeforeDrawObservable.notifyObservers(this);
  32329. var scene = this.getScene();
  32330. var engine = scene.getEngine();
  32331. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32332. // or triangles as points
  32333. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32334. }
  32335. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32336. // Triangles as wireframe
  32337. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32338. }
  32339. else {
  32340. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32341. }
  32342. if (scene._isAlternateRenderingEnabled && !alternate) {
  32343. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32344. if (!effect || !scene.activeCamera) {
  32345. return this;
  32346. }
  32347. scene._switchToAlternateCameraConfiguration(true);
  32348. this._effectiveMaterial.bindView(effect);
  32349. this._effectiveMaterial.bindViewProjection(effect);
  32350. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32351. this._draw(subMesh, fillMode, instancesCount, true);
  32352. engine.setViewport(scene.activeCamera.viewport);
  32353. scene._switchToAlternateCameraConfiguration(false);
  32354. this._effectiveMaterial.bindView(effect);
  32355. this._effectiveMaterial.bindViewProjection(effect);
  32356. }
  32357. return this;
  32358. };
  32359. /**
  32360. * Registers for this mesh a javascript function called just before the rendering process.
  32361. * This function is passed the current mesh.
  32362. * Return the Mesh.
  32363. */
  32364. Mesh.prototype.registerBeforeRender = function (func) {
  32365. this.onBeforeRenderObservable.add(func);
  32366. return this;
  32367. };
  32368. /**
  32369. * Disposes a previously registered javascript function called before the rendering.
  32370. * This function is passed the current mesh.
  32371. * Returns the Mesh.
  32372. */
  32373. Mesh.prototype.unregisterBeforeRender = function (func) {
  32374. this.onBeforeRenderObservable.removeCallback(func);
  32375. return this;
  32376. };
  32377. /**
  32378. * Registers for this mesh a javascript function called just after the rendering is complete.
  32379. * This function is passed the current mesh.
  32380. * Returns the Mesh.
  32381. */
  32382. Mesh.prototype.registerAfterRender = function (func) {
  32383. this.onAfterRenderObservable.add(func);
  32384. return this;
  32385. };
  32386. /**
  32387. * Disposes a previously registered javascript function called after the rendering.
  32388. * This function is passed the current mesh.
  32389. * Return the Mesh.
  32390. */
  32391. Mesh.prototype.unregisterAfterRender = function (func) {
  32392. this.onAfterRenderObservable.removeCallback(func);
  32393. return this;
  32394. };
  32395. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32396. var scene = this.getScene();
  32397. this._batchCache.mustReturn = false;
  32398. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32399. this._batchCache.visibleInstances[subMeshId] = null;
  32400. if (this._visibleInstances) {
  32401. var currentRenderId = scene.getRenderId();
  32402. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32403. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32404. var selfRenderId = this._renderId;
  32405. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32406. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32407. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32408. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32409. }
  32410. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32411. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32412. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32413. this._batchCache.mustReturn = true;
  32414. return this._batchCache;
  32415. }
  32416. if (currentRenderId !== selfRenderId) {
  32417. this._batchCache.renderSelf[subMeshId] = false;
  32418. }
  32419. }
  32420. this._renderIdForInstances[subMeshId] = currentRenderId;
  32421. }
  32422. return this._batchCache;
  32423. };
  32424. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32425. var visibleInstances = batch.visibleInstances[subMesh._id];
  32426. if (!visibleInstances) {
  32427. return this;
  32428. }
  32429. var matricesCount = visibleInstances.length + 1;
  32430. var bufferSize = matricesCount * 16 * 4;
  32431. var currentInstancesBufferSize = this._instancesBufferSize;
  32432. var instancesBuffer = this._instancesBuffer;
  32433. while (this._instancesBufferSize < bufferSize) {
  32434. this._instancesBufferSize *= 2;
  32435. }
  32436. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32437. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32438. }
  32439. var offset = 0;
  32440. var instancesCount = 0;
  32441. var world = this.getWorldMatrix();
  32442. if (batch.renderSelf[subMesh._id]) {
  32443. world.copyToArray(this._instancesData, offset);
  32444. offset += 16;
  32445. instancesCount++;
  32446. }
  32447. if (visibleInstances) {
  32448. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32449. var instance = visibleInstances[instanceIndex];
  32450. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32451. offset += 16;
  32452. instancesCount++;
  32453. }
  32454. }
  32455. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32456. if (instancesBuffer) {
  32457. instancesBuffer.dispose();
  32458. }
  32459. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32460. this._instancesBuffer = instancesBuffer;
  32461. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32462. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32463. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32464. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32465. }
  32466. else {
  32467. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32468. }
  32469. this._bind(subMesh, effect, fillMode);
  32470. this._draw(subMesh, fillMode, instancesCount);
  32471. engine.unbindInstanceAttributes();
  32472. return this;
  32473. };
  32474. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32475. var scene = this.getScene();
  32476. var engine = scene.getEngine();
  32477. if (hardwareInstancedRendering) {
  32478. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32479. }
  32480. else {
  32481. if (batch.renderSelf[subMesh._id]) {
  32482. // Draw
  32483. if (onBeforeDraw) {
  32484. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32485. }
  32486. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32487. }
  32488. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32489. if (visibleInstancesForSubMesh) {
  32490. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32491. var instance = visibleInstancesForSubMesh[instanceIndex];
  32492. // World
  32493. var world = instance.getWorldMatrix();
  32494. if (onBeforeDraw) {
  32495. onBeforeDraw(true, world, effectiveMaterial);
  32496. }
  32497. // Draw
  32498. this._draw(subMesh, fillMode);
  32499. }
  32500. }
  32501. }
  32502. return this;
  32503. };
  32504. /**
  32505. * Triggers the draw call for the mesh.
  32506. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32507. * Returns the Mesh.
  32508. */
  32509. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32510. this._checkOcclusionQuery();
  32511. if (this._isOccluded) {
  32512. return this;
  32513. }
  32514. var scene = this.getScene();
  32515. // Managing instances
  32516. var batch = this._getInstancesRenderList(subMesh._id);
  32517. if (batch.mustReturn) {
  32518. return this;
  32519. }
  32520. // Checking geometry state
  32521. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32522. return this;
  32523. }
  32524. this.onBeforeRenderObservable.notifyObservers(this);
  32525. var engine = scene.getEngine();
  32526. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32527. // Material
  32528. var material = subMesh.getMaterial();
  32529. if (!material) {
  32530. return this;
  32531. }
  32532. this._effectiveMaterial = material;
  32533. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32534. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32535. return this;
  32536. }
  32537. }
  32538. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32539. return this;
  32540. }
  32541. // Alpha mode
  32542. if (enableAlphaMode) {
  32543. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32544. }
  32545. // Outline - step 1
  32546. var savedDepthWrite = engine.getDepthWrite();
  32547. if (this.renderOutline) {
  32548. engine.setDepthWrite(false);
  32549. scene.getOutlineRenderer().render(subMesh, batch);
  32550. engine.setDepthWrite(savedDepthWrite);
  32551. }
  32552. var effect;
  32553. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32554. effect = subMesh.effect;
  32555. }
  32556. else {
  32557. effect = this._effectiveMaterial.getEffect();
  32558. }
  32559. if (!effect) {
  32560. return this;
  32561. }
  32562. var sideOrientation = this.overrideMaterialSideOrientation;
  32563. if (sideOrientation == null) {
  32564. sideOrientation = this._effectiveMaterial.sideOrientation;
  32565. if (this._getWorldMatrixDeterminant() < 0) {
  32566. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32567. }
  32568. }
  32569. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32570. if (this._effectiveMaterial.forceDepthWrite) {
  32571. engine.setDepthWrite(true);
  32572. }
  32573. // Bind
  32574. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32575. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32576. this._bind(subMesh, effect, fillMode);
  32577. }
  32578. var world = this.getWorldMatrix();
  32579. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32580. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32581. }
  32582. else {
  32583. this._effectiveMaterial.bind(world, this);
  32584. }
  32585. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32586. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32587. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32588. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32589. }
  32590. // Draw
  32591. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32592. // Unbind
  32593. this._effectiveMaterial.unbind();
  32594. // Outline - step 2
  32595. if (this.renderOutline && savedDepthWrite) {
  32596. engine.setDepthWrite(true);
  32597. engine.setColorWrite(false);
  32598. scene.getOutlineRenderer().render(subMesh, batch);
  32599. engine.setColorWrite(true);
  32600. }
  32601. // Overlay
  32602. if (this.renderOverlay) {
  32603. var currentMode = engine.getAlphaMode();
  32604. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32605. scene.getOutlineRenderer().render(subMesh, batch, true);
  32606. engine.setAlphaMode(currentMode);
  32607. }
  32608. this.onAfterRenderObservable.notifyObservers(this);
  32609. return this;
  32610. };
  32611. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32612. if (isInstance && effectiveMaterial) {
  32613. effectiveMaterial.bindOnlyWorldMatrix(world);
  32614. }
  32615. };
  32616. /**
  32617. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32618. */
  32619. Mesh.prototype.getEmittedParticleSystems = function () {
  32620. var results = new Array();
  32621. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32622. var particleSystem = this.getScene().particleSystems[index];
  32623. if (particleSystem.emitter === this) {
  32624. results.push(particleSystem);
  32625. }
  32626. }
  32627. return results;
  32628. };
  32629. /**
  32630. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32631. */
  32632. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32633. var results = new Array();
  32634. var descendants = this.getDescendants();
  32635. descendants.push(this);
  32636. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32637. var particleSystem = this.getScene().particleSystems[index];
  32638. var emitter = particleSystem.emitter;
  32639. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32640. results.push(particleSystem);
  32641. }
  32642. }
  32643. return results;
  32644. };
  32645. /**
  32646. * Normalize matrix weights so that all vertices have a total weight set to 1
  32647. */
  32648. Mesh.prototype.cleanMatrixWeights = function () {
  32649. var epsilon = 1e-3;
  32650. var noInfluenceBoneIndex = 0.0;
  32651. if (this.skeleton) {
  32652. noInfluenceBoneIndex = this.skeleton.bones.length;
  32653. }
  32654. else {
  32655. return;
  32656. }
  32657. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32658. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32659. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32660. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32661. var influencers = this.numBoneInfluencers;
  32662. var size = matricesWeights.length;
  32663. for (var i = 0; i < size; i += 4) {
  32664. var weight = 0.0;
  32665. var firstZeroWeight = -1;
  32666. for (var j = 0; j < 4; j++) {
  32667. var w = matricesWeights[i + j];
  32668. weight += w;
  32669. if (w < epsilon && firstZeroWeight < 0) {
  32670. firstZeroWeight = j;
  32671. }
  32672. }
  32673. if (matricesWeightsExtra) {
  32674. for (var j = 0; j < 4; j++) {
  32675. var w = matricesWeightsExtra[i + j];
  32676. weight += w;
  32677. if (w < epsilon && firstZeroWeight < 0) {
  32678. firstZeroWeight = j + 4;
  32679. }
  32680. }
  32681. }
  32682. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32683. firstZeroWeight = influencers - 1;
  32684. }
  32685. if (weight > epsilon) {
  32686. var mweight = 1.0 / weight;
  32687. for (var j = 0; j < 4; j++) {
  32688. matricesWeights[i + j] *= mweight;
  32689. }
  32690. if (matricesWeightsExtra) {
  32691. for (var j = 0; j < 4; j++) {
  32692. matricesWeightsExtra[i + j] *= mweight;
  32693. }
  32694. }
  32695. }
  32696. else {
  32697. if (firstZeroWeight >= 4) {
  32698. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32699. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32700. }
  32701. else {
  32702. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32703. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32704. }
  32705. }
  32706. }
  32707. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32708. if (matricesIndicesExtra) {
  32709. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32710. }
  32711. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32712. if (matricesWeightsExtra) {
  32713. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32714. }
  32715. };
  32716. Mesh.prototype._checkDelayState = function () {
  32717. var scene = this.getScene();
  32718. if (this._geometry) {
  32719. this._geometry.load(scene);
  32720. }
  32721. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32722. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32723. this._queueLoad(scene);
  32724. }
  32725. return this;
  32726. };
  32727. Mesh.prototype._queueLoad = function (scene) {
  32728. var _this = this;
  32729. scene._addPendingData(this);
  32730. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32731. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32732. if (data instanceof ArrayBuffer) {
  32733. _this._delayLoadingFunction(data, _this);
  32734. }
  32735. else {
  32736. _this._delayLoadingFunction(JSON.parse(data), _this);
  32737. }
  32738. _this.instances.forEach(function (instance) {
  32739. instance._syncSubMeshes();
  32740. });
  32741. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32742. scene._removePendingData(_this);
  32743. }, function () { }, scene.database, getBinaryData);
  32744. return this;
  32745. };
  32746. /**
  32747. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32748. */
  32749. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32750. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32751. return false;
  32752. }
  32753. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32754. return false;
  32755. }
  32756. this._checkDelayState();
  32757. return true;
  32758. };
  32759. /**
  32760. * Sets the mesh material by the material or multiMaterial `id` property.
  32761. * The material `id` is a string identifying the material or the multiMaterial.
  32762. * This method returns the Mesh.
  32763. */
  32764. Mesh.prototype.setMaterialByID = function (id) {
  32765. var materials = this.getScene().materials;
  32766. var index;
  32767. for (index = materials.length - 1; index > -1; index--) {
  32768. if (materials[index].id === id) {
  32769. this.material = materials[index];
  32770. return this;
  32771. }
  32772. }
  32773. // Multi
  32774. var multiMaterials = this.getScene().multiMaterials;
  32775. for (index = multiMaterials.length - 1; index > -1; index--) {
  32776. if (multiMaterials[index].id === id) {
  32777. this.material = multiMaterials[index];
  32778. return this;
  32779. }
  32780. }
  32781. return this;
  32782. };
  32783. /**
  32784. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32785. */
  32786. Mesh.prototype.getAnimatables = function () {
  32787. var results = new Array();
  32788. if (this.material) {
  32789. results.push(this.material);
  32790. }
  32791. if (this.skeleton) {
  32792. results.push(this.skeleton);
  32793. }
  32794. return results;
  32795. };
  32796. /**
  32797. * Modifies the mesh geometry according to the passed transformation matrix.
  32798. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32799. * The mesh normals are modified accordingly the same transformation.
  32800. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32801. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32802. * Returns the Mesh.
  32803. */
  32804. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32805. // Position
  32806. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32807. return this;
  32808. }
  32809. var submeshes = this.subMeshes.splice(0);
  32810. this._resetPointsArrayCache();
  32811. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32812. var temp = new Array();
  32813. var index;
  32814. for (index = 0; index < data.length; index += 3) {
  32815. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32816. }
  32817. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32818. // Normals
  32819. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32820. return this;
  32821. }
  32822. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32823. temp = [];
  32824. for (index = 0; index < data.length; index += 3) {
  32825. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32826. }
  32827. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32828. // flip faces?
  32829. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32830. this.flipFaces();
  32831. }
  32832. // Restore submeshes
  32833. this.releaseSubMeshes();
  32834. this.subMeshes = submeshes;
  32835. return this;
  32836. };
  32837. /**
  32838. * Modifies the mesh geometry according to its own current World Matrix.
  32839. * The mesh World Matrix is then reset.
  32840. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32841. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32842. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32843. * Returns the Mesh.
  32844. */
  32845. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32846. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32847. this.scaling.copyFromFloats(1, 1, 1);
  32848. this.position.copyFromFloats(0, 0, 0);
  32849. this.rotation.copyFromFloats(0, 0, 0);
  32850. //only if quaternion is already set
  32851. if (this.rotationQuaternion) {
  32852. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32853. }
  32854. this._worldMatrix = BABYLON.Matrix.Identity();
  32855. return this;
  32856. };
  32857. Object.defineProperty(Mesh.prototype, "_positions", {
  32858. // Cache
  32859. get: function () {
  32860. if (this._geometry) {
  32861. return this._geometry._positions;
  32862. }
  32863. return null;
  32864. },
  32865. enumerable: true,
  32866. configurable: true
  32867. });
  32868. Mesh.prototype._resetPointsArrayCache = function () {
  32869. if (this._geometry) {
  32870. this._geometry._resetPointsArrayCache();
  32871. }
  32872. return this;
  32873. };
  32874. Mesh.prototype._generatePointsArray = function () {
  32875. if (this._geometry) {
  32876. return this._geometry._generatePointsArray();
  32877. }
  32878. return false;
  32879. };
  32880. /**
  32881. * Returns a new Mesh object generated from the current mesh properties.
  32882. * This method must not get confused with createInstance().
  32883. * The parameter `name` is a string, the name given to the new mesh.
  32884. * The optional parameter `newParent` can be any Node object (default `null`).
  32885. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32886. * 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.
  32887. */
  32888. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32889. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32890. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32891. };
  32892. /**
  32893. * Releases resources associated with this mesh.
  32894. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32895. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32896. */
  32897. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32898. var _this = this;
  32899. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32900. this.morphTargetManager = null;
  32901. if (this._geometry) {
  32902. this._geometry.releaseForMesh(this, true);
  32903. }
  32904. // Sources
  32905. var meshes = this.getScene().meshes;
  32906. meshes.forEach(function (abstractMesh) {
  32907. var mesh = abstractMesh;
  32908. if (mesh._source && mesh._source === _this) {
  32909. mesh._source = null;
  32910. }
  32911. });
  32912. this._source = null;
  32913. // Instances
  32914. if (this._instancesBuffer) {
  32915. this._instancesBuffer.dispose();
  32916. this._instancesBuffer = null;
  32917. }
  32918. while (this.instances.length) {
  32919. this.instances[0].dispose();
  32920. }
  32921. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32922. };
  32923. /**
  32924. * Modifies the mesh geometry according to a displacement map.
  32925. * 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.
  32926. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32927. * This method returns nothing.
  32928. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32929. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32930. * 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.
  32931. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32932. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32933. *
  32934. * Returns the Mesh.
  32935. */
  32936. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32937. var _this = this;
  32938. var scene = this.getScene();
  32939. var onload = function (img) {
  32940. // Getting height map data
  32941. var canvas = document.createElement("canvas");
  32942. var context = canvas.getContext("2d");
  32943. var heightMapWidth = img.width;
  32944. var heightMapHeight = img.height;
  32945. canvas.width = heightMapWidth;
  32946. canvas.height = heightMapHeight;
  32947. context.drawImage(img, 0, 0);
  32948. // Create VertexData from map data
  32949. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32950. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32951. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32952. //execute success callback, if set
  32953. if (onSuccess) {
  32954. onSuccess(_this);
  32955. }
  32956. };
  32957. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32958. return this;
  32959. };
  32960. /**
  32961. * Modifies the mesh geometry according to a displacementMap buffer.
  32962. * 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.
  32963. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32964. * This method returns nothing.
  32965. * 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.
  32966. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32967. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32968. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32969. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32970. *
  32971. * Returns the Mesh.
  32972. */
  32973. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32974. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32975. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32976. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32977. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32978. return this;
  32979. }
  32980. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32981. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32982. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32983. var position = BABYLON.Vector3.Zero();
  32984. var normal = BABYLON.Vector3.Zero();
  32985. var uv = BABYLON.Vector2.Zero();
  32986. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32987. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32988. for (var index = 0; index < positions.length; index += 3) {
  32989. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32990. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32991. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32992. // Compute height
  32993. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32994. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32995. var pos = (u + v * heightMapWidth) * 4;
  32996. var r = buffer[pos] / 255.0;
  32997. var g = buffer[pos + 1] / 255.0;
  32998. var b = buffer[pos + 2] / 255.0;
  32999. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33000. normal.normalize();
  33001. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33002. position = position.add(normal);
  33003. position.toArray(positions, index);
  33004. }
  33005. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33006. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33007. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33008. return this;
  33009. };
  33010. /**
  33011. * Modify the mesh to get a flat shading rendering.
  33012. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33013. * This method returns the Mesh.
  33014. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33015. */
  33016. Mesh.prototype.convertToFlatShadedMesh = function () {
  33017. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33018. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33019. var kinds = this.getVerticesDataKinds();
  33020. var vbs = {};
  33021. var data = {};
  33022. var newdata = {};
  33023. var updatableNormals = false;
  33024. var kindIndex;
  33025. var kind;
  33026. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33027. kind = kinds[kindIndex];
  33028. var vertexBuffer = this.getVertexBuffer(kind);
  33029. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33030. updatableNormals = vertexBuffer.isUpdatable();
  33031. kinds.splice(kindIndex, 1);
  33032. kindIndex--;
  33033. continue;
  33034. }
  33035. vbs[kind] = vertexBuffer;
  33036. data[kind] = vbs[kind].getData();
  33037. newdata[kind] = [];
  33038. }
  33039. // Save previous submeshes
  33040. var previousSubmeshes = this.subMeshes.slice(0);
  33041. var indices = this.getIndices();
  33042. var totalIndices = this.getTotalIndices();
  33043. // Generating unique vertices per face
  33044. var index;
  33045. for (index = 0; index < totalIndices; index++) {
  33046. var vertexIndex = indices[index];
  33047. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33048. kind = kinds[kindIndex];
  33049. var stride = vbs[kind].getStrideSize();
  33050. for (var offset = 0; offset < stride; offset++) {
  33051. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33052. }
  33053. }
  33054. }
  33055. // Updating faces & normal
  33056. var normals = [];
  33057. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33058. for (index = 0; index < totalIndices; index += 3) {
  33059. indices[index] = index;
  33060. indices[index + 1] = index + 1;
  33061. indices[index + 2] = index + 2;
  33062. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33063. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33064. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33065. var p1p2 = p1.subtract(p2);
  33066. var p3p2 = p3.subtract(p2);
  33067. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33068. // Store same normals for every vertex
  33069. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33070. normals.push(normal.x);
  33071. normals.push(normal.y);
  33072. normals.push(normal.z);
  33073. }
  33074. }
  33075. this.setIndices(indices);
  33076. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33077. // Updating vertex buffers
  33078. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33079. kind = kinds[kindIndex];
  33080. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33081. }
  33082. // Updating submeshes
  33083. this.releaseSubMeshes();
  33084. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33085. var previousOne = previousSubmeshes[submeshIndex];
  33086. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33087. }
  33088. this.synchronizeInstances();
  33089. return this;
  33090. };
  33091. /**
  33092. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33093. * In other words, more vertices, no more indices and a single bigger VBO.
  33094. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33095. * Returns the Mesh.
  33096. */
  33097. Mesh.prototype.convertToUnIndexedMesh = function () {
  33098. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33099. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33100. var kinds = this.getVerticesDataKinds();
  33101. var vbs = {};
  33102. var data = {};
  33103. var newdata = {};
  33104. var kindIndex;
  33105. var kind;
  33106. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33107. kind = kinds[kindIndex];
  33108. var vertexBuffer = this.getVertexBuffer(kind);
  33109. vbs[kind] = vertexBuffer;
  33110. data[kind] = vbs[kind].getData();
  33111. newdata[kind] = [];
  33112. }
  33113. // Save previous submeshes
  33114. var previousSubmeshes = this.subMeshes.slice(0);
  33115. var indices = this.getIndices();
  33116. var totalIndices = this.getTotalIndices();
  33117. // Generating unique vertices per face
  33118. var index;
  33119. for (index = 0; index < totalIndices; index++) {
  33120. var vertexIndex = indices[index];
  33121. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33122. kind = kinds[kindIndex];
  33123. var stride = vbs[kind].getStrideSize();
  33124. for (var offset = 0; offset < stride; offset++) {
  33125. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33126. }
  33127. }
  33128. }
  33129. // Updating indices
  33130. for (index = 0; index < totalIndices; index += 3) {
  33131. indices[index] = index;
  33132. indices[index + 1] = index + 1;
  33133. indices[index + 2] = index + 2;
  33134. }
  33135. this.setIndices(indices);
  33136. // Updating vertex buffers
  33137. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33138. kind = kinds[kindIndex];
  33139. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33140. }
  33141. // Updating submeshes
  33142. this.releaseSubMeshes();
  33143. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33144. var previousOne = previousSubmeshes[submeshIndex];
  33145. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33146. }
  33147. this._unIndexed = true;
  33148. this.synchronizeInstances();
  33149. return this;
  33150. };
  33151. /**
  33152. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33153. * This method returns the Mesh.
  33154. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33155. */
  33156. Mesh.prototype.flipFaces = function (flipNormals) {
  33157. if (flipNormals === void 0) { flipNormals = false; }
  33158. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33159. var i;
  33160. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33161. for (i = 0; i < vertex_data.normals.length; i++) {
  33162. vertex_data.normals[i] *= -1;
  33163. }
  33164. }
  33165. if (vertex_data.indices) {
  33166. var temp;
  33167. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33168. // reassign indices
  33169. temp = vertex_data.indices[i + 1];
  33170. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33171. vertex_data.indices[i + 2] = temp;
  33172. }
  33173. }
  33174. vertex_data.applyToMesh(this);
  33175. return this;
  33176. };
  33177. // Instances
  33178. /**
  33179. * Creates a new InstancedMesh object from the mesh model.
  33180. * An instance shares the same properties and the same material than its model.
  33181. * Only these properties of each instance can then be set individually :
  33182. * - position
  33183. * - rotation
  33184. * - rotationQuaternion
  33185. * - setPivotMatrix
  33186. * - scaling
  33187. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33188. * Warning : this method is not supported for Line mesh and LineSystem
  33189. */
  33190. Mesh.prototype.createInstance = function (name) {
  33191. return new BABYLON.InstancedMesh(name, this);
  33192. };
  33193. /**
  33194. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33195. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33196. * This method returns the Mesh.
  33197. */
  33198. Mesh.prototype.synchronizeInstances = function () {
  33199. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33200. var instance = this.instances[instanceIndex];
  33201. instance._syncSubMeshes();
  33202. }
  33203. return this;
  33204. };
  33205. /**
  33206. * Simplify the mesh according to the given array of settings.
  33207. * Function will return immediately and will simplify async. It returns the Mesh.
  33208. * @param settings a collection of simplification settings.
  33209. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33210. * @param type the type of simplification to run.
  33211. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33212. */
  33213. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33214. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33215. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33216. this.getScene().simplificationQueue.addTask({
  33217. settings: settings,
  33218. parallelProcessing: parallelProcessing,
  33219. mesh: this,
  33220. simplificationType: simplificationType,
  33221. successCallback: successCallback
  33222. });
  33223. return this;
  33224. };
  33225. /**
  33226. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33227. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33228. * This should be used together with the simplification to avoid disappearing triangles.
  33229. * Returns the Mesh.
  33230. * @param successCallback an optional success callback to be called after the optimization finished.
  33231. */
  33232. Mesh.prototype.optimizeIndices = function (successCallback) {
  33233. var _this = this;
  33234. var indices = this.getIndices();
  33235. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33236. if (!positions || !indices) {
  33237. return this;
  33238. }
  33239. var vectorPositions = new Array();
  33240. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33241. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33242. }
  33243. var dupes = new Array();
  33244. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33245. var realPos = vectorPositions.length - 1 - iteration;
  33246. var testedPosition = vectorPositions[realPos];
  33247. for (var j = 0; j < realPos; ++j) {
  33248. var againstPosition = vectorPositions[j];
  33249. if (testedPosition.equals(againstPosition)) {
  33250. dupes[realPos] = j;
  33251. break;
  33252. }
  33253. }
  33254. }, function () {
  33255. for (var i = 0; i < indices.length; ++i) {
  33256. indices[i] = dupes[indices[i]] || indices[i];
  33257. }
  33258. //indices are now reordered
  33259. var originalSubMeshes = _this.subMeshes.slice(0);
  33260. _this.setIndices(indices);
  33261. _this.subMeshes = originalSubMeshes;
  33262. if (successCallback) {
  33263. successCallback(_this);
  33264. }
  33265. });
  33266. return this;
  33267. };
  33268. Mesh.prototype.serialize = function (serializationObject) {
  33269. serializationObject.name = this.name;
  33270. serializationObject.id = this.id;
  33271. serializationObject.type = this.getClassName();
  33272. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33273. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33274. }
  33275. serializationObject.position = this.position.asArray();
  33276. if (this.rotationQuaternion) {
  33277. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33278. }
  33279. else if (this.rotation) {
  33280. serializationObject.rotation = this.rotation.asArray();
  33281. }
  33282. serializationObject.scaling = this.scaling.asArray();
  33283. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33284. serializationObject.isEnabled = this.isEnabled(false);
  33285. serializationObject.isVisible = this.isVisible;
  33286. serializationObject.infiniteDistance = this.infiniteDistance;
  33287. serializationObject.pickable = this.isPickable;
  33288. serializationObject.receiveShadows = this.receiveShadows;
  33289. serializationObject.billboardMode = this.billboardMode;
  33290. serializationObject.visibility = this.visibility;
  33291. serializationObject.checkCollisions = this.checkCollisions;
  33292. serializationObject.isBlocker = this.isBlocker;
  33293. // Parent
  33294. if (this.parent) {
  33295. serializationObject.parentId = this.parent.id;
  33296. }
  33297. // Geometry
  33298. serializationObject.isUnIndexed = this.isUnIndexed;
  33299. var geometry = this._geometry;
  33300. if (geometry) {
  33301. var geometryId = geometry.id;
  33302. serializationObject.geometryId = geometryId;
  33303. // SubMeshes
  33304. serializationObject.subMeshes = [];
  33305. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33306. var subMesh = this.subMeshes[subIndex];
  33307. serializationObject.subMeshes.push({
  33308. materialIndex: subMesh.materialIndex,
  33309. verticesStart: subMesh.verticesStart,
  33310. verticesCount: subMesh.verticesCount,
  33311. indexStart: subMesh.indexStart,
  33312. indexCount: subMesh.indexCount
  33313. });
  33314. }
  33315. }
  33316. // Material
  33317. if (this.material) {
  33318. serializationObject.materialId = this.material.id;
  33319. }
  33320. else {
  33321. this.material = null;
  33322. }
  33323. // Morph targets
  33324. if (this.morphTargetManager) {
  33325. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33326. }
  33327. // Skeleton
  33328. if (this.skeleton) {
  33329. serializationObject.skeletonId = this.skeleton.id;
  33330. }
  33331. // Physics
  33332. //TODO implement correct serialization for physics impostors.
  33333. var impostor = this.getPhysicsImpostor();
  33334. if (impostor) {
  33335. serializationObject.physicsMass = impostor.getParam("mass");
  33336. serializationObject.physicsFriction = impostor.getParam("friction");
  33337. serializationObject.physicsRestitution = impostor.getParam("mass");
  33338. serializationObject.physicsImpostor = impostor.type;
  33339. }
  33340. // Metadata
  33341. if (this.metadata) {
  33342. serializationObject.metadata = this.metadata;
  33343. }
  33344. // Instances
  33345. serializationObject.instances = [];
  33346. for (var index = 0; index < this.instances.length; index++) {
  33347. var instance = this.instances[index];
  33348. var serializationInstance = {
  33349. name: instance.name,
  33350. id: instance.id,
  33351. position: instance.position.asArray(),
  33352. scaling: instance.scaling.asArray()
  33353. };
  33354. if (instance.rotationQuaternion) {
  33355. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33356. }
  33357. else if (instance.rotation) {
  33358. serializationInstance.rotation = instance.rotation.asArray();
  33359. }
  33360. serializationObject.instances.push(serializationInstance);
  33361. // Animations
  33362. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33363. serializationInstance.ranges = instance.serializeAnimationRanges();
  33364. }
  33365. //
  33366. // Animations
  33367. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33368. serializationObject.ranges = this.serializeAnimationRanges();
  33369. // Layer mask
  33370. serializationObject.layerMask = this.layerMask;
  33371. // Alpha
  33372. serializationObject.alphaIndex = this.alphaIndex;
  33373. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33374. // Overlay
  33375. serializationObject.overlayAlpha = this.overlayAlpha;
  33376. serializationObject.overlayColor = this.overlayColor.asArray();
  33377. serializationObject.renderOverlay = this.renderOverlay;
  33378. // Fog
  33379. serializationObject.applyFog = this.applyFog;
  33380. // Action Manager
  33381. if (this.actionManager) {
  33382. serializationObject.actions = this.actionManager.serialize(this.name);
  33383. }
  33384. };
  33385. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33386. if (!this.geometry) {
  33387. return;
  33388. }
  33389. this._markSubMeshesAsAttributesDirty();
  33390. var morphTargetManager = this._morphTargetManager;
  33391. if (morphTargetManager && morphTargetManager.vertexCount) {
  33392. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33393. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33394. this.morphTargetManager = null;
  33395. return;
  33396. }
  33397. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33398. var morphTarget = morphTargetManager.getActiveTarget(index);
  33399. var positions = morphTarget.getPositions();
  33400. if (!positions) {
  33401. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33402. return;
  33403. }
  33404. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33405. var normals = morphTarget.getNormals();
  33406. if (normals) {
  33407. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33408. }
  33409. var tangents = morphTarget.getTangents();
  33410. if (tangents) {
  33411. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33412. }
  33413. }
  33414. }
  33415. else {
  33416. var index = 0;
  33417. // Positions
  33418. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33419. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33420. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33421. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33422. }
  33423. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33424. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33425. }
  33426. index++;
  33427. }
  33428. }
  33429. };
  33430. // Statics
  33431. /**
  33432. * Returns a new Mesh object parsed from the source provided.
  33433. * The parameter `parsedMesh` is the source.
  33434. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33435. */
  33436. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33437. var mesh;
  33438. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33439. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33440. }
  33441. else {
  33442. mesh = new Mesh(parsedMesh.name, scene);
  33443. }
  33444. mesh.id = parsedMesh.id;
  33445. if (BABYLON.Tags) {
  33446. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33447. }
  33448. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33449. if (parsedMesh.metadata !== undefined) {
  33450. mesh.metadata = parsedMesh.metadata;
  33451. }
  33452. if (parsedMesh.rotationQuaternion) {
  33453. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33454. }
  33455. else if (parsedMesh.rotation) {
  33456. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33457. }
  33458. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33459. if (parsedMesh.localMatrix) {
  33460. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33461. }
  33462. else if (parsedMesh.pivotMatrix) {
  33463. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33464. }
  33465. mesh.setEnabled(parsedMesh.isEnabled);
  33466. mesh.isVisible = parsedMesh.isVisible;
  33467. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33468. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33469. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33470. if (parsedMesh.applyFog !== undefined) {
  33471. mesh.applyFog = parsedMesh.applyFog;
  33472. }
  33473. if (parsedMesh.pickable !== undefined) {
  33474. mesh.isPickable = parsedMesh.pickable;
  33475. }
  33476. if (parsedMesh.alphaIndex !== undefined) {
  33477. mesh.alphaIndex = parsedMesh.alphaIndex;
  33478. }
  33479. mesh.receiveShadows = parsedMesh.receiveShadows;
  33480. mesh.billboardMode = parsedMesh.billboardMode;
  33481. if (parsedMesh.visibility !== undefined) {
  33482. mesh.visibility = parsedMesh.visibility;
  33483. }
  33484. mesh.checkCollisions = parsedMesh.checkCollisions;
  33485. if (parsedMesh.isBlocker !== undefined) {
  33486. mesh.isBlocker = parsedMesh.isBlocker;
  33487. }
  33488. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33489. // freezeWorldMatrix
  33490. if (parsedMesh.freezeWorldMatrix) {
  33491. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33492. }
  33493. // Parent
  33494. if (parsedMesh.parentId) {
  33495. mesh._waitingParentId = parsedMesh.parentId;
  33496. }
  33497. // Actions
  33498. if (parsedMesh.actions !== undefined) {
  33499. mesh._waitingActions = parsedMesh.actions;
  33500. }
  33501. // Overlay
  33502. if (parsedMesh.overlayAlpha !== undefined) {
  33503. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33504. }
  33505. if (parsedMesh.overlayColor !== undefined) {
  33506. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33507. }
  33508. if (parsedMesh.renderOverlay !== undefined) {
  33509. mesh.renderOverlay = parsedMesh.renderOverlay;
  33510. }
  33511. // Geometry
  33512. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33513. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33514. if (parsedMesh.delayLoadingFile) {
  33515. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33516. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33517. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33518. if (parsedMesh._binaryInfo) {
  33519. mesh._binaryInfo = parsedMesh._binaryInfo;
  33520. }
  33521. mesh._delayInfo = [];
  33522. if (parsedMesh.hasUVs) {
  33523. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33524. }
  33525. if (parsedMesh.hasUVs2) {
  33526. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33527. }
  33528. if (parsedMesh.hasUVs3) {
  33529. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33530. }
  33531. if (parsedMesh.hasUVs4) {
  33532. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33533. }
  33534. if (parsedMesh.hasUVs5) {
  33535. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33536. }
  33537. if (parsedMesh.hasUVs6) {
  33538. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33539. }
  33540. if (parsedMesh.hasColors) {
  33541. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33542. }
  33543. if (parsedMesh.hasMatricesIndices) {
  33544. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33545. }
  33546. if (parsedMesh.hasMatricesWeights) {
  33547. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33548. }
  33549. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33550. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33551. mesh._checkDelayState();
  33552. }
  33553. }
  33554. else {
  33555. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33556. }
  33557. // Material
  33558. if (parsedMesh.materialId) {
  33559. mesh.setMaterialByID(parsedMesh.materialId);
  33560. }
  33561. else {
  33562. mesh.material = null;
  33563. }
  33564. // Morph targets
  33565. if (parsedMesh.morphTargetManagerId > -1) {
  33566. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33567. }
  33568. // Skeleton
  33569. if (parsedMesh.skeletonId > -1) {
  33570. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33571. if (parsedMesh.numBoneInfluencers) {
  33572. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33573. }
  33574. }
  33575. // Animations
  33576. if (parsedMesh.animations) {
  33577. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33578. var parsedAnimation = parsedMesh.animations[animationIndex];
  33579. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33580. }
  33581. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33582. }
  33583. if (parsedMesh.autoAnimate) {
  33584. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33585. }
  33586. // Layer Mask
  33587. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33588. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33589. }
  33590. else {
  33591. mesh.layerMask = 0x0FFFFFFF;
  33592. }
  33593. // Physics
  33594. if (parsedMesh.physicsImpostor) {
  33595. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33596. mass: parsedMesh.physicsMass,
  33597. friction: parsedMesh.physicsFriction,
  33598. restitution: parsedMesh.physicsRestitution
  33599. }, scene);
  33600. }
  33601. // Instances
  33602. if (parsedMesh.instances) {
  33603. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33604. var parsedInstance = parsedMesh.instances[index];
  33605. var instance = mesh.createInstance(parsedInstance.name);
  33606. if (parsedInstance.id) {
  33607. instance.id = parsedInstance.id;
  33608. }
  33609. if (BABYLON.Tags) {
  33610. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33611. }
  33612. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33613. if (parsedInstance.parentId) {
  33614. instance._waitingParentId = parsedInstance.parentId;
  33615. }
  33616. if (parsedInstance.rotationQuaternion) {
  33617. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33618. }
  33619. else if (parsedInstance.rotation) {
  33620. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33621. }
  33622. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33623. instance.checkCollisions = mesh.checkCollisions;
  33624. if (parsedMesh.animations) {
  33625. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33626. parsedAnimation = parsedMesh.animations[animationIndex];
  33627. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33628. }
  33629. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33630. if (parsedMesh.autoAnimate) {
  33631. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33632. }
  33633. }
  33634. }
  33635. }
  33636. return mesh;
  33637. };
  33638. /**
  33639. * Creates a ribbon mesh.
  33640. * Please consider using the same method from the MeshBuilder class instead.
  33641. * 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.
  33642. *
  33643. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33644. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33645. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33646. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33647. * 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.
  33648. * 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.
  33649. * 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
  33650. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33651. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33652. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33653. */
  33654. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33655. if (closeArray === void 0) { closeArray = false; }
  33656. if (updatable === void 0) { updatable = false; }
  33657. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33658. pathArray: pathArray,
  33659. closeArray: closeArray,
  33660. closePath: closePath,
  33661. offset: offset,
  33662. updatable: updatable,
  33663. sideOrientation: sideOrientation,
  33664. instance: instance
  33665. }, scene);
  33666. };
  33667. /**
  33668. * Creates a plane polygonal mesh. By default, this is a disc.
  33669. * Please consider using the same method from the MeshBuilder class instead.
  33670. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33671. * 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.
  33672. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33673. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33674. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33675. */
  33676. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33677. if (scene === void 0) { scene = null; }
  33678. var options = {
  33679. radius: radius,
  33680. tessellation: tessellation,
  33681. sideOrientation: sideOrientation,
  33682. updatable: updatable
  33683. };
  33684. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33685. };
  33686. /**
  33687. * Creates a box mesh.
  33688. * Please consider using the same method from the MeshBuilder class instead.
  33689. * The parameter `size` sets the size (float) of each box side (default 1).
  33690. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33691. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33693. */
  33694. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33695. if (scene === void 0) { scene = null; }
  33696. var options = {
  33697. size: size,
  33698. sideOrientation: sideOrientation,
  33699. updatable: updatable
  33700. };
  33701. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33702. };
  33703. /**
  33704. * Creates a sphere mesh.
  33705. * Please consider using the same method from the MeshBuilder class instead.
  33706. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33707. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33708. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33709. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33711. */
  33712. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33713. var options = {
  33714. segments: segments,
  33715. diameterX: diameter,
  33716. diameterY: diameter,
  33717. diameterZ: diameter,
  33718. sideOrientation: sideOrientation,
  33719. updatable: updatable
  33720. };
  33721. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33722. };
  33723. /**
  33724. * Creates a cylinder or a cone mesh.
  33725. * Please consider using the same method from the MeshBuilder class instead.
  33726. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33727. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33728. * 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.
  33729. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33730. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33731. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33732. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33733. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33734. */
  33735. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33736. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33737. if (scene !== undefined) {
  33738. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33739. updatable = scene;
  33740. }
  33741. scene = subdivisions;
  33742. subdivisions = 1;
  33743. }
  33744. var options = {
  33745. height: height,
  33746. diameterTop: diameterTop,
  33747. diameterBottom: diameterBottom,
  33748. tessellation: tessellation,
  33749. subdivisions: subdivisions,
  33750. sideOrientation: sideOrientation,
  33751. updatable: updatable
  33752. };
  33753. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33754. };
  33755. // Torus (Code from SharpDX.org)
  33756. /**
  33757. * Creates a torus mesh.
  33758. * Please consider using the same method from the MeshBuilder class instead.
  33759. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33760. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33761. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33762. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33763. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33764. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33765. */
  33766. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33767. var options = {
  33768. diameter: diameter,
  33769. thickness: thickness,
  33770. tessellation: tessellation,
  33771. sideOrientation: sideOrientation,
  33772. updatable: updatable
  33773. };
  33774. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33775. };
  33776. /**
  33777. * Creates a torus knot mesh.
  33778. * Please consider using the same method from the MeshBuilder class instead.
  33779. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33780. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33781. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33782. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33783. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33784. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33785. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33786. */
  33787. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33788. var options = {
  33789. radius: radius,
  33790. tube: tube,
  33791. radialSegments: radialSegments,
  33792. tubularSegments: tubularSegments,
  33793. p: p,
  33794. q: q,
  33795. sideOrientation: sideOrientation,
  33796. updatable: updatable
  33797. };
  33798. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33799. };
  33800. /**
  33801. * Creates a line mesh.
  33802. * Please consider using the same method from the MeshBuilder class instead.
  33803. * 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.
  33804. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33805. * The parameter `points` is an array successive Vector3.
  33806. * 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
  33807. * When updating an instance, remember that only point positions can change, not the number of points.
  33808. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33809. */
  33810. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33811. if (scene === void 0) { scene = null; }
  33812. if (updatable === void 0) { updatable = false; }
  33813. if (instance === void 0) { instance = null; }
  33814. var options = {
  33815. points: points,
  33816. updatable: updatable,
  33817. instance: instance
  33818. };
  33819. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33820. };
  33821. /**
  33822. * Creates a dashed line mesh.
  33823. * Please consider using the same method from the MeshBuilder class instead.
  33824. * 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.
  33825. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33826. * The parameter `points` is an array successive Vector3.
  33827. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33828. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33829. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33830. * 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
  33831. * When updating an instance, remember that only point positions can change, not the number of points.
  33832. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33833. */
  33834. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33835. if (scene === void 0) { scene = null; }
  33836. var options = {
  33837. points: points,
  33838. dashSize: dashSize,
  33839. gapSize: gapSize,
  33840. dashNb: dashNb,
  33841. updatable: updatable,
  33842. instance: instance
  33843. };
  33844. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33845. };
  33846. /**
  33847. * Creates a polygon mesh.
  33848. * Please consider using the same method from the MeshBuilder class instead.
  33849. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33850. * 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.
  33851. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33852. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33853. * Remember you can only change the shape positions, not their number when updating a polygon.
  33854. */
  33855. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33856. var options = {
  33857. shape: shape,
  33858. holes: holes,
  33859. updatable: updatable,
  33860. sideOrientation: sideOrientation
  33861. };
  33862. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33863. };
  33864. /**
  33865. * Creates an extruded polygon mesh, with depth in the Y direction.
  33866. * Please consider using the same method from the MeshBuilder class instead.
  33867. */
  33868. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33869. var options = {
  33870. shape: shape,
  33871. holes: holes,
  33872. depth: depth,
  33873. updatable: updatable,
  33874. sideOrientation: sideOrientation
  33875. };
  33876. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33877. };
  33878. /**
  33879. * Creates an extruded shape mesh.
  33880. * 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.
  33881. * Please consider using the same method from the MeshBuilder class instead.
  33882. *
  33883. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33884. * 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
  33885. * extruded along the Z axis.
  33886. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33887. * 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.
  33888. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33889. * 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
  33890. * 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
  33891. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33892. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33893. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33894. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33895. */
  33896. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33897. if (scene === void 0) { scene = null; }
  33898. var options = {
  33899. shape: shape,
  33900. path: path,
  33901. scale: scale,
  33902. rotation: rotation,
  33903. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33904. sideOrientation: sideOrientation,
  33905. instance: instance,
  33906. updatable: updatable
  33907. };
  33908. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33909. };
  33910. /**
  33911. * Creates an custom extruded shape mesh.
  33912. * 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.
  33913. * Please consider using the same method from the MeshBuilder class instead.
  33914. *
  33915. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33916. * 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
  33917. * extruded along the Z axis.
  33918. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33919. * 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
  33920. * and the distance of this point from the begining of the path :
  33921. * ```javascript
  33922. * var rotationFunction = function(i, distance) {
  33923. * // do things
  33924. * return rotationValue; }
  33925. * ```
  33926. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33927. * 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
  33928. * and the distance of this point from the begining of the path :
  33929. * ```javascript
  33930. * var scaleFunction = function(i, distance) {
  33931. * // do things
  33932. * return scaleValue;}
  33933. * ```
  33934. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33935. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33936. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33937. * 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
  33938. * 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
  33939. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33940. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33941. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33942. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33943. */
  33944. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33945. var options = {
  33946. shape: shape,
  33947. path: path,
  33948. scaleFunction: scaleFunction,
  33949. rotationFunction: rotationFunction,
  33950. ribbonCloseArray: ribbonCloseArray,
  33951. ribbonClosePath: ribbonClosePath,
  33952. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33953. sideOrientation: sideOrientation,
  33954. instance: instance,
  33955. updatable: updatable
  33956. };
  33957. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33958. };
  33959. /**
  33960. * Creates lathe mesh.
  33961. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33962. * Please consider using the same method from the MeshBuilder class instead.
  33963. * 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
  33964. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33965. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33966. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33967. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33968. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33969. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33970. */
  33971. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33972. var options = {
  33973. shape: shape,
  33974. radius: radius,
  33975. tessellation: tessellation,
  33976. sideOrientation: sideOrientation,
  33977. updatable: updatable
  33978. };
  33979. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33980. };
  33981. /**
  33982. * Creates a plane mesh.
  33983. * Please consider using the same method from the MeshBuilder class instead.
  33984. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33985. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33986. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33987. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33988. */
  33989. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33990. var options = {
  33991. size: size,
  33992. width: size,
  33993. height: size,
  33994. sideOrientation: sideOrientation,
  33995. updatable: updatable
  33996. };
  33997. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33998. };
  33999. /**
  34000. * Creates a ground mesh.
  34001. * Please consider using the same method from the MeshBuilder class instead.
  34002. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34003. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34004. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34005. */
  34006. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34007. var options = {
  34008. width: width,
  34009. height: height,
  34010. subdivisions: subdivisions,
  34011. updatable: updatable
  34012. };
  34013. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34014. };
  34015. /**
  34016. * Creates a tiled ground mesh.
  34017. * Please consider using the same method from the MeshBuilder class instead.
  34018. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34019. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34020. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34021. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34022. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34023. * numbers of subdivisions on the ground width and height of each tile.
  34024. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34025. */
  34026. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34027. var options = {
  34028. xmin: xmin,
  34029. zmin: zmin,
  34030. xmax: xmax,
  34031. zmax: zmax,
  34032. subdivisions: subdivisions,
  34033. precision: precision,
  34034. updatable: updatable
  34035. };
  34036. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34037. };
  34038. /**
  34039. * Creates a ground mesh from a height map.
  34040. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34041. * Please consider using the same method from the MeshBuilder class instead.
  34042. * The parameter `url` sets the URL of the height map image resource.
  34043. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34044. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34045. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34046. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34047. * 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).
  34048. * This function is passed the newly built mesh :
  34049. * ```javascript
  34050. * function(mesh) { // do things
  34051. * return; }
  34052. * ```
  34053. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34054. */
  34055. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34056. var options = {
  34057. width: width,
  34058. height: height,
  34059. subdivisions: subdivisions,
  34060. minHeight: minHeight,
  34061. maxHeight: maxHeight,
  34062. updatable: updatable,
  34063. onReady: onReady
  34064. };
  34065. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34066. };
  34067. /**
  34068. * Creates a tube mesh.
  34069. * 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.
  34070. * Please consider using the same method from the MeshBuilder class instead.
  34071. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34072. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34073. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34074. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34075. * 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.
  34076. * It must return a radius value (positive float) :
  34077. * ```javascript
  34078. * var radiusFunction = function(i, distance) {
  34079. * // do things
  34080. * return radius; }
  34081. * ```
  34082. * 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
  34083. * 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
  34084. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34085. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34086. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34087. */
  34088. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34089. var options = {
  34090. path: path,
  34091. radius: radius,
  34092. tessellation: tessellation,
  34093. radiusFunction: radiusFunction,
  34094. arc: 1,
  34095. cap: cap,
  34096. updatable: updatable,
  34097. sideOrientation: sideOrientation,
  34098. instance: instance
  34099. };
  34100. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34101. };
  34102. /**
  34103. * Creates a polyhedron mesh.
  34104. * Please consider using the same method from the MeshBuilder class instead.
  34105. * 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
  34106. * to choose the wanted type.
  34107. * The parameter `size` (positive float, default 1) sets the polygon size.
  34108. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34109. * 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`.
  34110. * 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
  34111. * 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)`).
  34112. * 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
  34113. * 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.
  34114. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34115. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34116. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34117. */
  34118. Mesh.CreatePolyhedron = function (name, options, scene) {
  34119. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34120. };
  34121. /**
  34122. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34123. * Please consider using the same method from the MeshBuilder class instead.
  34124. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34125. * 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`).
  34126. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34127. * 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.
  34128. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34129. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34130. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34131. */
  34132. Mesh.CreateIcoSphere = function (name, options, scene) {
  34133. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34134. };
  34135. /**
  34136. * Creates a decal mesh.
  34137. * Please consider using the same method from the MeshBuilder class instead.
  34138. * 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.
  34139. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34140. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34141. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34142. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34143. */
  34144. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34145. var options = {
  34146. position: position,
  34147. normal: normal,
  34148. size: size,
  34149. angle: angle
  34150. };
  34151. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34152. };
  34153. // Skeletons
  34154. /**
  34155. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34156. */
  34157. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34158. if (!this._sourcePositions) {
  34159. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34160. if (!source) {
  34161. return this._sourcePositions;
  34162. }
  34163. this._sourcePositions = new Float32Array(source);
  34164. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34165. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34166. }
  34167. }
  34168. return this._sourcePositions;
  34169. };
  34170. /**
  34171. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34172. */
  34173. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34174. if (!this._sourceNormals) {
  34175. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34176. if (!source) {
  34177. return this._sourceNormals;
  34178. }
  34179. this._sourceNormals = new Float32Array(source);
  34180. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34181. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34182. }
  34183. }
  34184. return this._sourceNormals;
  34185. };
  34186. /**
  34187. * Updates the vertex buffer by applying transformation from the bones.
  34188. * Returns the Mesh.
  34189. *
  34190. * @param {skeleton} skeleton to apply
  34191. */
  34192. Mesh.prototype.applySkeleton = function (skeleton) {
  34193. if (!this.geometry) {
  34194. return this;
  34195. }
  34196. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34197. return this;
  34198. }
  34199. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34200. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34201. return this;
  34202. }
  34203. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34204. return this;
  34205. }
  34206. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34207. return this;
  34208. }
  34209. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34210. return this;
  34211. }
  34212. if (!this._sourcePositions) {
  34213. var submeshes = this.subMeshes.slice();
  34214. this.setPositionsForCPUSkinning();
  34215. this.subMeshes = submeshes;
  34216. }
  34217. if (!this._sourceNormals) {
  34218. this.setNormalsForCPUSkinning();
  34219. }
  34220. // positionsData checks for not being Float32Array will only pass at most once
  34221. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34222. if (!positionsData) {
  34223. return this;
  34224. }
  34225. if (!(positionsData instanceof Float32Array)) {
  34226. positionsData = new Float32Array(positionsData);
  34227. }
  34228. // normalsData checks for not being Float32Array will only pass at most once
  34229. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34230. if (!normalsData) {
  34231. return this;
  34232. }
  34233. if (!(normalsData instanceof Float32Array)) {
  34234. normalsData = new Float32Array(normalsData);
  34235. }
  34236. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34237. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34238. if (!matricesWeightsData || !matricesIndicesData) {
  34239. return this;
  34240. }
  34241. var needExtras = this.numBoneInfluencers > 4;
  34242. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34243. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34244. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34245. var tempVector3 = BABYLON.Vector3.Zero();
  34246. var finalMatrix = new BABYLON.Matrix();
  34247. var tempMatrix = new BABYLON.Matrix();
  34248. var matWeightIdx = 0;
  34249. var inf;
  34250. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34251. var weight;
  34252. for (inf = 0; inf < 4; inf++) {
  34253. weight = matricesWeightsData[matWeightIdx + inf];
  34254. if (weight > 0) {
  34255. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34256. finalMatrix.addToSelf(tempMatrix);
  34257. }
  34258. else
  34259. break;
  34260. }
  34261. if (needExtras) {
  34262. for (inf = 0; inf < 4; inf++) {
  34263. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34264. if (weight > 0) {
  34265. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34266. finalMatrix.addToSelf(tempMatrix);
  34267. }
  34268. else
  34269. break;
  34270. }
  34271. }
  34272. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34273. tempVector3.toArray(positionsData, index);
  34274. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34275. tempVector3.toArray(normalsData, index);
  34276. finalMatrix.reset();
  34277. }
  34278. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34279. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34280. return this;
  34281. };
  34282. // Tools
  34283. /**
  34284. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34285. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34286. */
  34287. Mesh.MinMax = function (meshes) {
  34288. var minVector = null;
  34289. var maxVector = null;
  34290. meshes.forEach(function (mesh, index, array) {
  34291. var boundingInfo = mesh.getBoundingInfo();
  34292. var boundingBox = boundingInfo.boundingBox;
  34293. if (!minVector || !maxVector) {
  34294. minVector = boundingBox.minimumWorld;
  34295. maxVector = boundingBox.maximumWorld;
  34296. }
  34297. else {
  34298. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34299. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34300. }
  34301. });
  34302. if (!minVector || !maxVector) {
  34303. return {
  34304. min: BABYLON.Vector3.Zero(),
  34305. max: BABYLON.Vector3.Zero()
  34306. };
  34307. }
  34308. return {
  34309. min: minVector,
  34310. max: maxVector
  34311. };
  34312. };
  34313. /**
  34314. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34315. */
  34316. Mesh.Center = function (meshesOrMinMaxVector) {
  34317. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34318. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34319. };
  34320. /**
  34321. * Merge the array of meshes into a single mesh for performance reasons.
  34322. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34323. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34324. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34325. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34326. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34327. */
  34328. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34329. if (disposeSource === void 0) { disposeSource = true; }
  34330. var index;
  34331. if (!allow32BitsIndices) {
  34332. var totalVertices = 0;
  34333. // Counting vertices
  34334. for (index = 0; index < meshes.length; index++) {
  34335. if (meshes[index]) {
  34336. totalVertices += meshes[index].getTotalVertices();
  34337. if (totalVertices > 65536) {
  34338. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34339. return null;
  34340. }
  34341. }
  34342. }
  34343. }
  34344. // Merge
  34345. var vertexData = null;
  34346. var otherVertexData;
  34347. var indiceArray = new Array();
  34348. var source = null;
  34349. for (index = 0; index < meshes.length; index++) {
  34350. if (meshes[index]) {
  34351. meshes[index].computeWorldMatrix(true);
  34352. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34353. otherVertexData.transform(meshes[index].getWorldMatrix());
  34354. if (vertexData) {
  34355. vertexData.merge(otherVertexData);
  34356. }
  34357. else {
  34358. vertexData = otherVertexData;
  34359. source = meshes[index];
  34360. }
  34361. if (subdivideWithSubMeshes) {
  34362. indiceArray.push(meshes[index].getTotalIndices());
  34363. }
  34364. }
  34365. }
  34366. source = source;
  34367. if (!meshSubclass) {
  34368. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34369. }
  34370. vertexData.applyToMesh(meshSubclass);
  34371. // Setting properties
  34372. meshSubclass.material = source.material;
  34373. meshSubclass.checkCollisions = source.checkCollisions;
  34374. // Cleaning
  34375. if (disposeSource) {
  34376. for (index = 0; index < meshes.length; index++) {
  34377. if (meshes[index]) {
  34378. meshes[index].dispose();
  34379. }
  34380. }
  34381. }
  34382. // Subdivide
  34383. if (subdivideWithSubMeshes) {
  34384. //-- removal of global submesh
  34385. meshSubclass.releaseSubMeshes();
  34386. index = 0;
  34387. var offset = 0;
  34388. //-- apply subdivision according to index table
  34389. while (index < indiceArray.length) {
  34390. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34391. offset += indiceArray[index];
  34392. index++;
  34393. }
  34394. }
  34395. return meshSubclass;
  34396. };
  34397. // Consts
  34398. Mesh._FRONTSIDE = 0;
  34399. Mesh._BACKSIDE = 1;
  34400. Mesh._DOUBLESIDE = 2;
  34401. Mesh._DEFAULTSIDE = 0;
  34402. Mesh._NO_CAP = 0;
  34403. Mesh._CAP_START = 1;
  34404. Mesh._CAP_END = 2;
  34405. Mesh._CAP_ALL = 3;
  34406. return Mesh;
  34407. }(BABYLON.AbstractMesh));
  34408. BABYLON.Mesh = Mesh;
  34409. })(BABYLON || (BABYLON = {}));
  34410. //# sourceMappingURL=babylon.mesh.js.map
  34411. var BABYLON;
  34412. (function (BABYLON) {
  34413. var BaseSubMesh = /** @class */ (function () {
  34414. function BaseSubMesh() {
  34415. }
  34416. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34417. get: function () {
  34418. return this._materialEffect;
  34419. },
  34420. enumerable: true,
  34421. configurable: true
  34422. });
  34423. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34424. if (defines === void 0) { defines = null; }
  34425. if (this._materialEffect === effect) {
  34426. if (!effect) {
  34427. this._materialDefines = null;
  34428. }
  34429. return;
  34430. }
  34431. this._materialDefines = defines;
  34432. this._materialEffect = effect;
  34433. };
  34434. return BaseSubMesh;
  34435. }());
  34436. BABYLON.BaseSubMesh = BaseSubMesh;
  34437. var SubMesh = /** @class */ (function (_super) {
  34438. __extends(SubMesh, _super);
  34439. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34440. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34441. var _this = _super.call(this) || this;
  34442. _this.materialIndex = materialIndex;
  34443. _this.verticesStart = verticesStart;
  34444. _this.verticesCount = verticesCount;
  34445. _this.indexStart = indexStart;
  34446. _this.indexCount = indexCount;
  34447. _this._renderId = 0;
  34448. _this._mesh = mesh;
  34449. _this._renderingMesh = renderingMesh || mesh;
  34450. mesh.subMeshes.push(_this);
  34451. _this._trianglePlanes = [];
  34452. _this._id = mesh.subMeshes.length - 1;
  34453. if (createBoundingBox) {
  34454. _this.refreshBoundingInfo();
  34455. mesh.computeWorldMatrix(true);
  34456. }
  34457. return _this;
  34458. }
  34459. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34460. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34461. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34462. };
  34463. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34464. get: function () {
  34465. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34466. },
  34467. enumerable: true,
  34468. configurable: true
  34469. });
  34470. /**
  34471. * Returns the submesh BoudingInfo object.
  34472. */
  34473. SubMesh.prototype.getBoundingInfo = function () {
  34474. if (this.IsGlobal) {
  34475. return this._mesh.getBoundingInfo();
  34476. }
  34477. return this._boundingInfo;
  34478. };
  34479. /**
  34480. * Sets the submesh BoundingInfo.
  34481. * Return the SubMesh.
  34482. */
  34483. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34484. this._boundingInfo = boundingInfo;
  34485. return this;
  34486. };
  34487. /**
  34488. * Returns the mesh of the current submesh.
  34489. */
  34490. SubMesh.prototype.getMesh = function () {
  34491. return this._mesh;
  34492. };
  34493. /**
  34494. * Returns the rendering mesh of the submesh.
  34495. */
  34496. SubMesh.prototype.getRenderingMesh = function () {
  34497. return this._renderingMesh;
  34498. };
  34499. /**
  34500. * Returns the submesh material.
  34501. */
  34502. SubMesh.prototype.getMaterial = function () {
  34503. var rootMaterial = this._renderingMesh.material;
  34504. if (rootMaterial === null || rootMaterial === undefined) {
  34505. return this._mesh.getScene().defaultMaterial;
  34506. }
  34507. else if (rootMaterial.getSubMaterial) {
  34508. var multiMaterial = rootMaterial;
  34509. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34510. if (this._currentMaterial !== effectiveMaterial) {
  34511. this._currentMaterial = effectiveMaterial;
  34512. this._materialDefines = null;
  34513. }
  34514. return effectiveMaterial;
  34515. }
  34516. return rootMaterial;
  34517. };
  34518. // Methods
  34519. /**
  34520. * Sets a new updated BoundingInfo object to the submesh.
  34521. * Returns the SubMesh.
  34522. */
  34523. SubMesh.prototype.refreshBoundingInfo = function () {
  34524. this._lastColliderWorldVertices = null;
  34525. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34526. return this;
  34527. }
  34528. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34529. if (!data) {
  34530. this._boundingInfo = this._mesh.getBoundingInfo();
  34531. return this;
  34532. }
  34533. var indices = this._renderingMesh.getIndices();
  34534. var extend;
  34535. //is this the only submesh?
  34536. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34537. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34538. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34539. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34540. }
  34541. else {
  34542. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34543. }
  34544. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34545. return this;
  34546. };
  34547. SubMesh.prototype._checkCollision = function (collider) {
  34548. var boundingInfo = this.getBoundingInfo();
  34549. return boundingInfo._checkCollision(collider);
  34550. };
  34551. /**
  34552. * Updates the submesh BoundingInfo.
  34553. * Returns the Submesh.
  34554. */
  34555. SubMesh.prototype.updateBoundingInfo = function (world) {
  34556. var boundingInfo = this.getBoundingInfo();
  34557. if (!boundingInfo) {
  34558. this.refreshBoundingInfo();
  34559. boundingInfo = this.getBoundingInfo();
  34560. }
  34561. boundingInfo.update(world);
  34562. return this;
  34563. };
  34564. /**
  34565. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34566. * Boolean returned.
  34567. */
  34568. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34569. var boundingInfo = this.getBoundingInfo();
  34570. if (!boundingInfo) {
  34571. return false;
  34572. }
  34573. return boundingInfo.isInFrustum(frustumPlanes);
  34574. };
  34575. /**
  34576. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34577. * Boolean returned.
  34578. */
  34579. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34580. var boundingInfo = this.getBoundingInfo();
  34581. if (!boundingInfo) {
  34582. return false;
  34583. }
  34584. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34585. };
  34586. /**
  34587. * Renders the submesh.
  34588. * Returns it.
  34589. */
  34590. SubMesh.prototype.render = function (enableAlphaMode) {
  34591. this._renderingMesh.render(this, enableAlphaMode);
  34592. return this;
  34593. };
  34594. /**
  34595. * Returns a new Index Buffer.
  34596. * Type returned : WebGLBuffer.
  34597. */
  34598. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34599. if (!this._linesIndexBuffer) {
  34600. var linesIndices = [];
  34601. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34602. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34603. }
  34604. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34605. this.linesIndexCount = linesIndices.length;
  34606. }
  34607. return this._linesIndexBuffer;
  34608. };
  34609. /**
  34610. * True is the passed Ray intersects the submesh bounding box.
  34611. * Boolean returned.
  34612. */
  34613. SubMesh.prototype.canIntersects = function (ray) {
  34614. var boundingInfo = this.getBoundingInfo();
  34615. if (!boundingInfo) {
  34616. return false;
  34617. }
  34618. return ray.intersectsBox(boundingInfo.boundingBox);
  34619. };
  34620. /**
  34621. * Returns an object IntersectionInfo.
  34622. */
  34623. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34624. var intersectInfo = null;
  34625. var material = this.getMaterial();
  34626. if (!material) {
  34627. return null;
  34628. }
  34629. switch (material.fillMode) {
  34630. case BABYLON.Material.PointListDrawMode:
  34631. case BABYLON.Material.LineListDrawMode:
  34632. case BABYLON.Material.LineLoopDrawMode:
  34633. case BABYLON.Material.LineStripDrawMode:
  34634. case BABYLON.Material.TriangleFanDrawMode:
  34635. case BABYLON.Material.TriangleStripDrawMode:
  34636. return null;
  34637. }
  34638. // LineMesh first as it's also a Mesh...
  34639. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34640. var lineMesh = this._mesh;
  34641. // Line test
  34642. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34643. var p0 = positions[indices[index]];
  34644. var p1 = positions[indices[index + 1]];
  34645. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34646. if (length < 0) {
  34647. continue;
  34648. }
  34649. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34650. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34651. if (fastCheck) {
  34652. break;
  34653. }
  34654. }
  34655. }
  34656. }
  34657. else {
  34658. // Triangles test
  34659. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34660. var p0 = positions[indices[index]];
  34661. var p1 = positions[indices[index + 1]];
  34662. var p2 = positions[indices[index + 2]];
  34663. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34664. if (currentIntersectInfo) {
  34665. if (currentIntersectInfo.distance < 0) {
  34666. continue;
  34667. }
  34668. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34669. intersectInfo = currentIntersectInfo;
  34670. intersectInfo.faceId = index / 3;
  34671. if (fastCheck) {
  34672. break;
  34673. }
  34674. }
  34675. }
  34676. }
  34677. }
  34678. return intersectInfo;
  34679. };
  34680. SubMesh.prototype._rebuild = function () {
  34681. if (this._linesIndexBuffer) {
  34682. this._linesIndexBuffer = null;
  34683. }
  34684. };
  34685. // Clone
  34686. /**
  34687. * Creates a new Submesh from the passed Mesh.
  34688. */
  34689. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34690. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34691. if (!this.IsGlobal) {
  34692. var boundingInfo = this.getBoundingInfo();
  34693. if (!boundingInfo) {
  34694. return result;
  34695. }
  34696. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34697. }
  34698. return result;
  34699. };
  34700. // Dispose
  34701. /**
  34702. * Disposes the Submesh.
  34703. * Returns nothing.
  34704. */
  34705. SubMesh.prototype.dispose = function () {
  34706. if (this._linesIndexBuffer) {
  34707. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34708. this._linesIndexBuffer = null;
  34709. }
  34710. // Remove from mesh
  34711. var index = this._mesh.subMeshes.indexOf(this);
  34712. this._mesh.subMeshes.splice(index, 1);
  34713. };
  34714. // Statics
  34715. /**
  34716. * Creates a new Submesh from the passed parameters :
  34717. * - materialIndex (integer) : the index of the main mesh material.
  34718. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34719. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34720. * - mesh (Mesh) : the main mesh to create the submesh from.
  34721. * - renderingMesh (optional Mesh) : rendering mesh.
  34722. */
  34723. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34724. var minVertexIndex = Number.MAX_VALUE;
  34725. var maxVertexIndex = -Number.MAX_VALUE;
  34726. renderingMesh = (renderingMesh || mesh);
  34727. var indices = renderingMesh.getIndices();
  34728. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34729. var vertexIndex = indices[index];
  34730. if (vertexIndex < minVertexIndex)
  34731. minVertexIndex = vertexIndex;
  34732. if (vertexIndex > maxVertexIndex)
  34733. maxVertexIndex = vertexIndex;
  34734. }
  34735. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34736. };
  34737. return SubMesh;
  34738. }(BaseSubMesh));
  34739. BABYLON.SubMesh = SubMesh;
  34740. })(BABYLON || (BABYLON = {}));
  34741. //# sourceMappingURL=babylon.subMesh.js.map
  34742. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34743. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34744. s = arguments[i];
  34745. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34746. t[p] = s[p];
  34747. }
  34748. return t;
  34749. };
  34750. var BABYLON;
  34751. (function (BABYLON) {
  34752. /**
  34753. * Manages the defines for the Material
  34754. */
  34755. var MaterialDefines = /** @class */ (function () {
  34756. function MaterialDefines() {
  34757. this._isDirty = true;
  34758. /** @hidden */
  34759. this._areLightsDirty = true;
  34760. /** @hidden */
  34761. this._areAttributesDirty = true;
  34762. /** @hidden */
  34763. this._areTexturesDirty = true;
  34764. /** @hidden */
  34765. this._areFresnelDirty = true;
  34766. /** @hidden */
  34767. this._areMiscDirty = true;
  34768. /** @hidden */
  34769. this._areImageProcessingDirty = true;
  34770. /** @hidden */
  34771. this._normals = false;
  34772. /** @hidden */
  34773. this._uvs = false;
  34774. /** @hidden */
  34775. this._needNormals = false;
  34776. /** @hidden */
  34777. this._needUVs = false;
  34778. }
  34779. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34780. /**
  34781. * Specifies if the material needs to be re-calculated
  34782. */
  34783. get: function () {
  34784. return this._isDirty;
  34785. },
  34786. enumerable: true,
  34787. configurable: true
  34788. });
  34789. /**
  34790. * Marks the material to indicate that it has been re-calculated
  34791. */
  34792. MaterialDefines.prototype.markAsProcessed = function () {
  34793. this._isDirty = false;
  34794. this._areAttributesDirty = false;
  34795. this._areTexturesDirty = false;
  34796. this._areFresnelDirty = false;
  34797. this._areLightsDirty = false;
  34798. this._areMiscDirty = false;
  34799. this._areImageProcessingDirty = false;
  34800. };
  34801. /**
  34802. * Marks the material to indicate that it needs to be re-calculated
  34803. */
  34804. MaterialDefines.prototype.markAsUnprocessed = function () {
  34805. this._isDirty = true;
  34806. };
  34807. /**
  34808. * Marks the material to indicate all of its defines need to be re-calculated
  34809. */
  34810. MaterialDefines.prototype.markAllAsDirty = function () {
  34811. this._areTexturesDirty = true;
  34812. this._areAttributesDirty = true;
  34813. this._areLightsDirty = true;
  34814. this._areFresnelDirty = true;
  34815. this._areMiscDirty = true;
  34816. this._areImageProcessingDirty = true;
  34817. this._isDirty = true;
  34818. };
  34819. /**
  34820. * Marks the material to indicate that image processing needs to be re-calculated
  34821. */
  34822. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34823. this._areImageProcessingDirty = true;
  34824. this._isDirty = true;
  34825. };
  34826. /**
  34827. * Marks the material to indicate the lights need to be re-calculated
  34828. */
  34829. MaterialDefines.prototype.markAsLightDirty = function () {
  34830. this._areLightsDirty = true;
  34831. this._isDirty = true;
  34832. };
  34833. /**
  34834. * Marks the attribute state as changed
  34835. */
  34836. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34837. this._areAttributesDirty = true;
  34838. this._isDirty = true;
  34839. };
  34840. /**
  34841. * Marks the texture state as changed
  34842. */
  34843. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34844. this._areTexturesDirty = true;
  34845. this._isDirty = true;
  34846. };
  34847. /**
  34848. * Marks the fresnel state as changed
  34849. */
  34850. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34851. this._areFresnelDirty = true;
  34852. this._isDirty = true;
  34853. };
  34854. /**
  34855. * Marks the misc state as changed
  34856. */
  34857. MaterialDefines.prototype.markAsMiscDirty = function () {
  34858. this._areMiscDirty = true;
  34859. this._isDirty = true;
  34860. };
  34861. /**
  34862. * Rebuilds the material defines
  34863. */
  34864. MaterialDefines.prototype.rebuild = function () {
  34865. if (this._keys) {
  34866. delete this._keys;
  34867. }
  34868. this._keys = [];
  34869. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34870. var key = _a[_i];
  34871. if (key[0] === "_") {
  34872. continue;
  34873. }
  34874. this._keys.push(key);
  34875. }
  34876. };
  34877. /**
  34878. * Specifies if two material defines are equal
  34879. * @param other - A material define instance to compare to
  34880. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34881. */
  34882. MaterialDefines.prototype.isEqual = function (other) {
  34883. if (this._keys.length !== other._keys.length) {
  34884. return false;
  34885. }
  34886. for (var index = 0; index < this._keys.length; index++) {
  34887. var prop = this._keys[index];
  34888. if (this[prop] !== other[prop]) {
  34889. return false;
  34890. }
  34891. }
  34892. return true;
  34893. };
  34894. /**
  34895. * Clones this instance's defines to another instance
  34896. * @param other - material defines to clone values to
  34897. */
  34898. MaterialDefines.prototype.cloneTo = function (other) {
  34899. if (this._keys.length !== other._keys.length) {
  34900. other._keys = this._keys.slice(0);
  34901. }
  34902. for (var index = 0; index < this._keys.length; index++) {
  34903. var prop = this._keys[index];
  34904. other[prop] = this[prop];
  34905. }
  34906. };
  34907. /**
  34908. * Resets the material define values
  34909. */
  34910. MaterialDefines.prototype.reset = function () {
  34911. for (var index = 0; index < this._keys.length; index++) {
  34912. var prop = this._keys[index];
  34913. var type = typeof this[prop];
  34914. switch (type) {
  34915. case "number":
  34916. this[prop] = 0;
  34917. break;
  34918. case "string":
  34919. this[prop] = "";
  34920. break;
  34921. default:
  34922. this[prop] = false;
  34923. break;
  34924. }
  34925. }
  34926. };
  34927. /**
  34928. * Converts the material define values to a string
  34929. * @returns - String of material define information
  34930. */
  34931. MaterialDefines.prototype.toString = function () {
  34932. var result = "";
  34933. for (var index = 0; index < this._keys.length; index++) {
  34934. var prop = this._keys[index];
  34935. var value = this[prop];
  34936. var type = typeof value;
  34937. switch (type) {
  34938. case "number":
  34939. case "string":
  34940. result += "#define " + prop + " " + value + "\n";
  34941. break;
  34942. default:
  34943. if (value) {
  34944. result += "#define " + prop + "\n";
  34945. }
  34946. break;
  34947. }
  34948. }
  34949. return result;
  34950. };
  34951. return MaterialDefines;
  34952. }());
  34953. BABYLON.MaterialDefines = MaterialDefines;
  34954. /**
  34955. * Base class for the main features of a material in Babylon.js
  34956. */
  34957. var Material = /** @class */ (function () {
  34958. /**
  34959. * Creates a material instance
  34960. * @param name defines the name of the material
  34961. * @param scene defines the scene to reference
  34962. * @param doNotAdd specifies if the material should be added to the scene
  34963. */
  34964. function Material(name, scene, doNotAdd) {
  34965. /**
  34966. * Specifies if the ready state should be checked on each call
  34967. */
  34968. this.checkReadyOnEveryCall = false;
  34969. /**
  34970. * Specifies if the ready state should be checked once
  34971. */
  34972. this.checkReadyOnlyOnce = false;
  34973. /**
  34974. * The state of the material
  34975. */
  34976. this.state = "";
  34977. /**
  34978. * The alpha value of the material
  34979. */
  34980. this._alpha = 1.0;
  34981. /**
  34982. * Specifies if back face culling is enabled
  34983. */
  34984. this._backFaceCulling = true;
  34985. /**
  34986. * Specifies if the material should be serialized
  34987. */
  34988. this.doNotSerialize = false;
  34989. /**
  34990. * Specifies if the effect should be stored on sub meshes
  34991. */
  34992. this.storeEffectOnSubMeshes = false;
  34993. /**
  34994. * An event triggered when the material is disposed
  34995. */
  34996. this.onDisposeObservable = new BABYLON.Observable();
  34997. /**
  34998. * An event triggered when the material is bound
  34999. */
  35000. this.onBindObservable = new BABYLON.Observable();
  35001. /**
  35002. * An event triggered when the material is unbound
  35003. */
  35004. this.onUnBindObservable = new BABYLON.Observable();
  35005. /**
  35006. * Stores the value of the alpha mode
  35007. */
  35008. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35009. /**
  35010. * Stores the state of the need depth pre-pass value
  35011. */
  35012. this._needDepthPrePass = false;
  35013. /**
  35014. * Specifies if depth writing should be disabled
  35015. */
  35016. this.disableDepthWrite = false;
  35017. /**
  35018. * Specifies if depth writing should be forced
  35019. */
  35020. this.forceDepthWrite = false;
  35021. /**
  35022. * Specifies if there should be a separate pass for culling
  35023. */
  35024. this.separateCullingPass = false;
  35025. /**
  35026. * Stores the state specifing if fog should be enabled
  35027. */
  35028. this._fogEnabled = true;
  35029. /**
  35030. * Stores the size of points
  35031. */
  35032. this.pointSize = 1.0;
  35033. /**
  35034. * Stores the z offset value
  35035. */
  35036. this.zOffset = 0;
  35037. /**
  35038. * Specifies if the material was previously ready
  35039. */
  35040. this._wasPreviouslyReady = false;
  35041. /**
  35042. * Stores the fill mode state
  35043. */
  35044. this._fillMode = Material.TriangleFillMode;
  35045. this.name = name;
  35046. this.id = name || BABYLON.Tools.RandomId();
  35047. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35048. this.uniqueId = this._scene.getUniqueId();
  35049. if (this._scene.useRightHandedSystem) {
  35050. this.sideOrientation = Material.ClockWiseSideOrientation;
  35051. }
  35052. else {
  35053. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35054. }
  35055. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35056. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35057. if (!doNotAdd) {
  35058. this._scene.materials.push(this);
  35059. }
  35060. }
  35061. Object.defineProperty(Material, "TriangleFillMode", {
  35062. /**
  35063. * Returns the triangle fill mode
  35064. */
  35065. get: function () {
  35066. return Material._TriangleFillMode;
  35067. },
  35068. enumerable: true,
  35069. configurable: true
  35070. });
  35071. Object.defineProperty(Material, "WireFrameFillMode", {
  35072. /**
  35073. * Returns the wireframe mode
  35074. */
  35075. get: function () {
  35076. return Material._WireFrameFillMode;
  35077. },
  35078. enumerable: true,
  35079. configurable: true
  35080. });
  35081. Object.defineProperty(Material, "PointFillMode", {
  35082. /**
  35083. * Returns the point fill mode
  35084. */
  35085. get: function () {
  35086. return Material._PointFillMode;
  35087. },
  35088. enumerable: true,
  35089. configurable: true
  35090. });
  35091. Object.defineProperty(Material, "PointListDrawMode", {
  35092. /**
  35093. * Returns the point list draw mode
  35094. */
  35095. get: function () {
  35096. return Material._PointListDrawMode;
  35097. },
  35098. enumerable: true,
  35099. configurable: true
  35100. });
  35101. Object.defineProperty(Material, "LineListDrawMode", {
  35102. /**
  35103. * Returns the line list draw mode
  35104. */
  35105. get: function () {
  35106. return Material._LineListDrawMode;
  35107. },
  35108. enumerable: true,
  35109. configurable: true
  35110. });
  35111. Object.defineProperty(Material, "LineLoopDrawMode", {
  35112. /**
  35113. * Returns the line loop draw mode
  35114. */
  35115. get: function () {
  35116. return Material._LineLoopDrawMode;
  35117. },
  35118. enumerable: true,
  35119. configurable: true
  35120. });
  35121. Object.defineProperty(Material, "LineStripDrawMode", {
  35122. /**
  35123. * Returns the line strip draw mode
  35124. */
  35125. get: function () {
  35126. return Material._LineStripDrawMode;
  35127. },
  35128. enumerable: true,
  35129. configurable: true
  35130. });
  35131. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35132. /**
  35133. * Returns the triangle strip draw mode
  35134. */
  35135. get: function () {
  35136. return Material._TriangleStripDrawMode;
  35137. },
  35138. enumerable: true,
  35139. configurable: true
  35140. });
  35141. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35142. /**
  35143. * Returns the triangle fan draw mode
  35144. */
  35145. get: function () {
  35146. return Material._TriangleFanDrawMode;
  35147. },
  35148. enumerable: true,
  35149. configurable: true
  35150. });
  35151. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35152. /**
  35153. * Returns the clock-wise side orientation
  35154. */
  35155. get: function () {
  35156. return Material._ClockWiseSideOrientation;
  35157. },
  35158. enumerable: true,
  35159. configurable: true
  35160. });
  35161. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35162. /**
  35163. * Returns the counter clock-wise side orientation
  35164. */
  35165. get: function () {
  35166. return Material._CounterClockWiseSideOrientation;
  35167. },
  35168. enumerable: true,
  35169. configurable: true
  35170. });
  35171. Object.defineProperty(Material, "TextureDirtyFlag", {
  35172. /**
  35173. * Returns the dirty texture flag value
  35174. */
  35175. get: function () {
  35176. return Material._TextureDirtyFlag;
  35177. },
  35178. enumerable: true,
  35179. configurable: true
  35180. });
  35181. Object.defineProperty(Material, "LightDirtyFlag", {
  35182. /**
  35183. * Returns the dirty light flag value
  35184. */
  35185. get: function () {
  35186. return Material._LightDirtyFlag;
  35187. },
  35188. enumerable: true,
  35189. configurable: true
  35190. });
  35191. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35192. /**
  35193. * Returns the dirty fresnel flag value
  35194. */
  35195. get: function () {
  35196. return Material._FresnelDirtyFlag;
  35197. },
  35198. enumerable: true,
  35199. configurable: true
  35200. });
  35201. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35202. /**
  35203. * Returns the dirty attributes flag value
  35204. */
  35205. get: function () {
  35206. return Material._AttributesDirtyFlag;
  35207. },
  35208. enumerable: true,
  35209. configurable: true
  35210. });
  35211. Object.defineProperty(Material, "MiscDirtyFlag", {
  35212. /**
  35213. * Returns the dirty misc flag value
  35214. */
  35215. get: function () {
  35216. return Material._MiscDirtyFlag;
  35217. },
  35218. enumerable: true,
  35219. configurable: true
  35220. });
  35221. Object.defineProperty(Material.prototype, "alpha", {
  35222. /**
  35223. * Gets the alpha value of the material
  35224. */
  35225. get: function () {
  35226. return this._alpha;
  35227. },
  35228. /**
  35229. * Sets the alpha value of the material
  35230. */
  35231. set: function (value) {
  35232. if (this._alpha === value) {
  35233. return;
  35234. }
  35235. this._alpha = value;
  35236. this.markAsDirty(Material.MiscDirtyFlag);
  35237. },
  35238. enumerable: true,
  35239. configurable: true
  35240. });
  35241. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35242. /**
  35243. * Gets the back-face culling state
  35244. */
  35245. get: function () {
  35246. return this._backFaceCulling;
  35247. },
  35248. /**
  35249. * Sets the back-face culling state
  35250. */
  35251. set: function (value) {
  35252. if (this._backFaceCulling === value) {
  35253. return;
  35254. }
  35255. this._backFaceCulling = value;
  35256. this.markAsDirty(Material.TextureDirtyFlag);
  35257. },
  35258. enumerable: true,
  35259. configurable: true
  35260. });
  35261. Object.defineProperty(Material.prototype, "onDispose", {
  35262. /**
  35263. * Called during a dispose event
  35264. */
  35265. set: function (callback) {
  35266. if (this._onDisposeObserver) {
  35267. this.onDisposeObservable.remove(this._onDisposeObserver);
  35268. }
  35269. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35270. },
  35271. enumerable: true,
  35272. configurable: true
  35273. });
  35274. Object.defineProperty(Material.prototype, "onBind", {
  35275. /**
  35276. * Called during a bind event
  35277. */
  35278. set: function (callback) {
  35279. if (this._onBindObserver) {
  35280. this.onBindObservable.remove(this._onBindObserver);
  35281. }
  35282. this._onBindObserver = this.onBindObservable.add(callback);
  35283. },
  35284. enumerable: true,
  35285. configurable: true
  35286. });
  35287. Object.defineProperty(Material.prototype, "alphaMode", {
  35288. /**
  35289. * Gets the value of the alpha mode
  35290. */
  35291. get: function () {
  35292. return this._alphaMode;
  35293. },
  35294. /**
  35295. * Sets the value of the alpha mode.
  35296. *
  35297. * | Value | Type | Description |
  35298. * | --- | --- | --- |
  35299. * | 0 | ALPHA_DISABLE | |
  35300. * | 1 | ALPHA_ADD | |
  35301. * | 2 | ALPHA_COMBINE | |
  35302. * | 3 | ALPHA_SUBTRACT | |
  35303. * | 4 | ALPHA_MULTIPLY | |
  35304. * | 5 | ALPHA_MAXIMIZED | |
  35305. * | 6 | ALPHA_ONEONE | |
  35306. * | 7 | ALPHA_PREMULTIPLIED | |
  35307. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35308. * | 9 | ALPHA_INTERPOLATE | |
  35309. * | 10 | ALPHA_SCREENMODE | |
  35310. *
  35311. */
  35312. set: function (value) {
  35313. if (this._alphaMode === value) {
  35314. return;
  35315. }
  35316. this._alphaMode = value;
  35317. this.markAsDirty(Material.TextureDirtyFlag);
  35318. },
  35319. enumerable: true,
  35320. configurable: true
  35321. });
  35322. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35323. /**
  35324. * Gets the depth pre-pass value
  35325. */
  35326. get: function () {
  35327. return this._needDepthPrePass;
  35328. },
  35329. /**
  35330. * Sets the need depth pre-pass value
  35331. */
  35332. set: function (value) {
  35333. if (this._needDepthPrePass === value) {
  35334. return;
  35335. }
  35336. this._needDepthPrePass = value;
  35337. if (this._needDepthPrePass) {
  35338. this.checkReadyOnEveryCall = true;
  35339. }
  35340. },
  35341. enumerable: true,
  35342. configurable: true
  35343. });
  35344. Object.defineProperty(Material.prototype, "fogEnabled", {
  35345. /**
  35346. * Gets the value of the fog enabled state
  35347. */
  35348. get: function () {
  35349. return this._fogEnabled;
  35350. },
  35351. /**
  35352. * Sets the state for enabling fog
  35353. */
  35354. set: function (value) {
  35355. if (this._fogEnabled === value) {
  35356. return;
  35357. }
  35358. this._fogEnabled = value;
  35359. this.markAsDirty(Material.MiscDirtyFlag);
  35360. },
  35361. enumerable: true,
  35362. configurable: true
  35363. });
  35364. Object.defineProperty(Material.prototype, "wireframe", {
  35365. /**
  35366. * Gets a value specifying if wireframe mode is enabled
  35367. */
  35368. get: function () {
  35369. switch (this._fillMode) {
  35370. case Material.WireFrameFillMode:
  35371. case Material.LineListDrawMode:
  35372. case Material.LineLoopDrawMode:
  35373. case Material.LineStripDrawMode:
  35374. return true;
  35375. }
  35376. return this._scene.forceWireframe;
  35377. },
  35378. /**
  35379. * Sets the state of wireframe mode
  35380. */
  35381. set: function (value) {
  35382. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35383. },
  35384. enumerable: true,
  35385. configurable: true
  35386. });
  35387. Object.defineProperty(Material.prototype, "pointsCloud", {
  35388. /**
  35389. * Gets the value specifying if point clouds are enabled
  35390. */
  35391. get: function () {
  35392. switch (this._fillMode) {
  35393. case Material.PointFillMode:
  35394. case Material.PointListDrawMode:
  35395. return true;
  35396. }
  35397. return this._scene.forcePointsCloud;
  35398. },
  35399. /**
  35400. * Sets the state of point cloud mode
  35401. */
  35402. set: function (value) {
  35403. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35404. },
  35405. enumerable: true,
  35406. configurable: true
  35407. });
  35408. Object.defineProperty(Material.prototype, "fillMode", {
  35409. /**
  35410. * Gets the material fill mode
  35411. */
  35412. get: function () {
  35413. return this._fillMode;
  35414. },
  35415. /**
  35416. * Sets the material fill mode
  35417. */
  35418. set: function (value) {
  35419. if (this._fillMode === value) {
  35420. return;
  35421. }
  35422. this._fillMode = value;
  35423. this.markAsDirty(Material.MiscDirtyFlag);
  35424. },
  35425. enumerable: true,
  35426. configurable: true
  35427. });
  35428. /**
  35429. * Returns a string representation of the current material
  35430. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35431. * @returns a string with material information
  35432. */
  35433. Material.prototype.toString = function (fullDetails) {
  35434. var ret = "Name: " + this.name;
  35435. if (fullDetails) {
  35436. }
  35437. return ret;
  35438. };
  35439. /**
  35440. * Gets the class name of the material
  35441. * @returns a string with the class name of the material
  35442. */
  35443. Material.prototype.getClassName = function () {
  35444. return "Material";
  35445. };
  35446. Object.defineProperty(Material.prototype, "isFrozen", {
  35447. /**
  35448. * Specifies if updates for the material been locked
  35449. */
  35450. get: function () {
  35451. return this.checkReadyOnlyOnce;
  35452. },
  35453. enumerable: true,
  35454. configurable: true
  35455. });
  35456. /**
  35457. * Locks updates for the material
  35458. */
  35459. Material.prototype.freeze = function () {
  35460. this.checkReadyOnlyOnce = true;
  35461. };
  35462. /**
  35463. * Unlocks updates for the material
  35464. */
  35465. Material.prototype.unfreeze = function () {
  35466. this.checkReadyOnlyOnce = false;
  35467. };
  35468. /**
  35469. * Specifies if the material is ready to be used
  35470. * @param mesh defines the mesh to check
  35471. * @param useInstances specifies if instances should be used
  35472. * @returns a boolean indicating if the material is ready to be used
  35473. */
  35474. Material.prototype.isReady = function (mesh, useInstances) {
  35475. return true;
  35476. };
  35477. /**
  35478. * Specifies that the submesh is ready to be used
  35479. * @param mesh defines the mesh to check
  35480. * @param subMesh defines which submesh to check
  35481. * @param useInstances specifies that instances should be used
  35482. * @returns a boolean indicating that the submesh is ready or not
  35483. */
  35484. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35485. return false;
  35486. };
  35487. /**
  35488. * Returns the material effect
  35489. * @returns the effect associated with the material
  35490. */
  35491. Material.prototype.getEffect = function () {
  35492. return this._effect;
  35493. };
  35494. /**
  35495. * Returns the current scene
  35496. * @returns a Scene
  35497. */
  35498. Material.prototype.getScene = function () {
  35499. return this._scene;
  35500. };
  35501. /**
  35502. * Specifies if the material will require alpha blending
  35503. * @returns a boolean specifying if alpha blending is needed
  35504. */
  35505. Material.prototype.needAlphaBlending = function () {
  35506. return (this.alpha < 1.0);
  35507. };
  35508. /**
  35509. * Specifies if the mesh will require alpha blending
  35510. * @param mesh defines the mesh to check
  35511. * @returns a boolean specifying if alpha blending is needed for the mesh
  35512. */
  35513. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35514. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35515. };
  35516. /**
  35517. * Specifies if this material should be rendered in alpha test mode
  35518. * @returns a boolean specifying if an alpha test is needed.
  35519. */
  35520. Material.prototype.needAlphaTesting = function () {
  35521. return false;
  35522. };
  35523. /**
  35524. * Gets the texture used for the alpha test
  35525. * @returns the texture to use for alpha testing
  35526. */
  35527. Material.prototype.getAlphaTestTexture = function () {
  35528. return null;
  35529. };
  35530. /**
  35531. * Marks the material to indicate that it needs to be re-calculated
  35532. */
  35533. Material.prototype.markDirty = function () {
  35534. this._wasPreviouslyReady = false;
  35535. };
  35536. /** @hidden */
  35537. Material.prototype._preBind = function (effect, overrideOrientation) {
  35538. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35539. var engine = this._scene.getEngine();
  35540. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35541. var reverse = orientation === Material.ClockWiseSideOrientation;
  35542. engine.enableEffect(effect ? effect : this._effect);
  35543. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35544. return reverse;
  35545. };
  35546. /**
  35547. * Binds the material to the mesh
  35548. * @param world defines the world transformation matrix
  35549. * @param mesh defines the mesh to bind the material to
  35550. */
  35551. Material.prototype.bind = function (world, mesh) {
  35552. };
  35553. /**
  35554. * Binds the submesh to the material
  35555. * @param world defines the world transformation matrix
  35556. * @param mesh defines the mesh containing the submesh
  35557. * @param subMesh defines the submesh to bind the material to
  35558. */
  35559. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35560. };
  35561. /**
  35562. * Binds the world matrix to the material
  35563. * @param world defines the world transformation matrix
  35564. */
  35565. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35566. };
  35567. /**
  35568. * Binds the scene's uniform buffer to the effect.
  35569. * @param effect defines the effect to bind to the scene uniform buffer
  35570. * @param sceneUbo defines the uniform buffer storing scene data
  35571. */
  35572. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35573. sceneUbo.bindToEffect(effect, "Scene");
  35574. };
  35575. /**
  35576. * Binds the view matrix to the effect
  35577. * @param effect defines the effect to bind the view matrix to
  35578. */
  35579. Material.prototype.bindView = function (effect) {
  35580. if (!this._useUBO) {
  35581. effect.setMatrix("view", this.getScene().getViewMatrix());
  35582. }
  35583. else {
  35584. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35585. }
  35586. };
  35587. /**
  35588. * Binds the view projection matrix to the effect
  35589. * @param effect defines the effect to bind the view projection matrix to
  35590. */
  35591. Material.prototype.bindViewProjection = function (effect) {
  35592. if (!this._useUBO) {
  35593. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35594. }
  35595. else {
  35596. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35597. }
  35598. };
  35599. /**
  35600. * Specifies if material alpha testing should be turned on for the mesh
  35601. * @param mesh defines the mesh to check
  35602. */
  35603. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35604. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35605. };
  35606. /**
  35607. * Processes to execute after binding the material to a mesh
  35608. * @param mesh defines the rendered mesh
  35609. */
  35610. Material.prototype._afterBind = function (mesh) {
  35611. this._scene._cachedMaterial = this;
  35612. if (mesh) {
  35613. this._scene._cachedVisibility = mesh.visibility;
  35614. }
  35615. else {
  35616. this._scene._cachedVisibility = 1;
  35617. }
  35618. if (mesh) {
  35619. this.onBindObservable.notifyObservers(mesh);
  35620. }
  35621. if (this.disableDepthWrite) {
  35622. var engine = this._scene.getEngine();
  35623. this._cachedDepthWriteState = engine.getDepthWrite();
  35624. engine.setDepthWrite(false);
  35625. }
  35626. };
  35627. /**
  35628. * Unbinds the material from the mesh
  35629. */
  35630. Material.prototype.unbind = function () {
  35631. this.onUnBindObservable.notifyObservers(this);
  35632. if (this.disableDepthWrite) {
  35633. var engine = this._scene.getEngine();
  35634. engine.setDepthWrite(this._cachedDepthWriteState);
  35635. }
  35636. };
  35637. /**
  35638. * Gets the active textures from the material
  35639. * @returns an array of textures
  35640. */
  35641. Material.prototype.getActiveTextures = function () {
  35642. return [];
  35643. };
  35644. /**
  35645. * Specifies if the material uses a texture
  35646. * @param texture defines the texture to check against the material
  35647. * @returns a boolean specifying if the material uses the texture
  35648. */
  35649. Material.prototype.hasTexture = function (texture) {
  35650. return false;
  35651. };
  35652. /**
  35653. * Makes a duplicate of the material, and gives it a new name
  35654. * @param name defines the new name for the duplicated material
  35655. * @returns the cloned material
  35656. */
  35657. Material.prototype.clone = function (name) {
  35658. return null;
  35659. };
  35660. /**
  35661. * Gets the meshes bound to the material
  35662. * @returns an array of meshes bound to the material
  35663. */
  35664. Material.prototype.getBindedMeshes = function () {
  35665. var result = new Array();
  35666. for (var index = 0; index < this._scene.meshes.length; index++) {
  35667. var mesh = this._scene.meshes[index];
  35668. if (mesh.material === this) {
  35669. result.push(mesh);
  35670. }
  35671. }
  35672. return result;
  35673. };
  35674. /**
  35675. * Force shader compilation
  35676. * @param mesh defines the mesh associated with this material
  35677. * @param onCompiled defines a function to execute once the material is compiled
  35678. * @param options defines the options to configure the compilation
  35679. */
  35680. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35681. var _this = this;
  35682. var localOptions = __assign({ clipPlane: false }, options);
  35683. var subMesh = new BABYLON.BaseSubMesh();
  35684. var scene = this.getScene();
  35685. var checkReady = function () {
  35686. if (!_this._scene || !_this._scene.getEngine()) {
  35687. return;
  35688. }
  35689. if (subMesh._materialDefines) {
  35690. subMesh._materialDefines._renderId = -1;
  35691. }
  35692. var clipPlaneState = scene.clipPlane;
  35693. if (localOptions.clipPlane) {
  35694. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35695. }
  35696. if (_this.storeEffectOnSubMeshes) {
  35697. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35698. if (onCompiled) {
  35699. onCompiled(_this);
  35700. }
  35701. }
  35702. else {
  35703. setTimeout(checkReady, 16);
  35704. }
  35705. }
  35706. else {
  35707. if (_this.isReady(mesh)) {
  35708. if (onCompiled) {
  35709. onCompiled(_this);
  35710. }
  35711. }
  35712. else {
  35713. setTimeout(checkReady, 16);
  35714. }
  35715. }
  35716. if (localOptions.clipPlane) {
  35717. scene.clipPlane = clipPlaneState;
  35718. }
  35719. };
  35720. checkReady();
  35721. };
  35722. /**
  35723. * Force shader compilation
  35724. * @param mesh defines the mesh that will use this material
  35725. * @param options defines additional options for compiling the shaders
  35726. * @returns a promise that resolves when the compilation completes
  35727. */
  35728. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35729. var _this = this;
  35730. return new Promise(function (resolve) {
  35731. _this.forceCompilation(mesh, function () {
  35732. resolve();
  35733. }, options);
  35734. });
  35735. };
  35736. /**
  35737. * Marks a define in the material to indicate that it needs to be re-computed
  35738. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35739. */
  35740. Material.prototype.markAsDirty = function (flag) {
  35741. if (flag & Material.TextureDirtyFlag) {
  35742. this._markAllSubMeshesAsTexturesDirty();
  35743. }
  35744. if (flag & Material.LightDirtyFlag) {
  35745. this._markAllSubMeshesAsLightsDirty();
  35746. }
  35747. if (flag & Material.FresnelDirtyFlag) {
  35748. this._markAllSubMeshesAsFresnelDirty();
  35749. }
  35750. if (flag & Material.AttributesDirtyFlag) {
  35751. this._markAllSubMeshesAsAttributesDirty();
  35752. }
  35753. if (flag & Material.MiscDirtyFlag) {
  35754. this._markAllSubMeshesAsMiscDirty();
  35755. }
  35756. this.getScene().resetCachedMaterial();
  35757. };
  35758. /**
  35759. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35760. * @param func defines a function which checks material defines against the submeshes
  35761. */
  35762. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35763. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35764. var mesh = _a[_i];
  35765. if (!mesh.subMeshes) {
  35766. continue;
  35767. }
  35768. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35769. var subMesh = _c[_b];
  35770. if (subMesh.getMaterial() !== this) {
  35771. continue;
  35772. }
  35773. if (!subMesh._materialDefines) {
  35774. continue;
  35775. }
  35776. func(subMesh._materialDefines);
  35777. }
  35778. }
  35779. };
  35780. /**
  35781. * Indicates that image processing needs to be re-calculated for all submeshes
  35782. */
  35783. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35784. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35785. };
  35786. /**
  35787. * Indicates that textures need to be re-calculated for all submeshes
  35788. */
  35789. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35790. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35791. };
  35792. /**
  35793. * Indicates that fresnel needs to be re-calculated for all submeshes
  35794. */
  35795. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35796. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35797. };
  35798. /**
  35799. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35800. */
  35801. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35802. this._markAllSubMeshesAsDirty(function (defines) {
  35803. defines.markAsFresnelDirty();
  35804. defines.markAsMiscDirty();
  35805. });
  35806. };
  35807. /**
  35808. * Indicates that lights need to be re-calculated for all submeshes
  35809. */
  35810. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35811. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35812. };
  35813. /**
  35814. * Indicates that attributes need to be re-calculated for all submeshes
  35815. */
  35816. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35817. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35818. };
  35819. /**
  35820. * Indicates that misc needs to be re-calculated for all submeshes
  35821. */
  35822. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35823. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35824. };
  35825. /**
  35826. * Indicates that textures and misc need to be re-calculated for all submeshes
  35827. */
  35828. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35829. this._markAllSubMeshesAsDirty(function (defines) {
  35830. defines.markAsTexturesDirty();
  35831. defines.markAsMiscDirty();
  35832. });
  35833. };
  35834. /**
  35835. * Disposes the material
  35836. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35837. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35838. */
  35839. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35840. // Animations
  35841. this.getScene().stopAnimation(this);
  35842. this.getScene().freeProcessedMaterials();
  35843. // Remove from scene
  35844. var index = this._scene.materials.indexOf(this);
  35845. if (index >= 0) {
  35846. this._scene.materials.splice(index, 1);
  35847. }
  35848. // Remove from meshes
  35849. for (index = 0; index < this._scene.meshes.length; index++) {
  35850. var mesh = this._scene.meshes[index];
  35851. if (mesh.material === this) {
  35852. mesh.material = null;
  35853. if (mesh.geometry) {
  35854. var geometry = (mesh.geometry);
  35855. if (this.storeEffectOnSubMeshes) {
  35856. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35857. var subMesh = _a[_i];
  35858. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35859. if (forceDisposeEffect && subMesh._materialEffect) {
  35860. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35861. }
  35862. }
  35863. }
  35864. else {
  35865. geometry._releaseVertexArrayObject(this._effect);
  35866. }
  35867. }
  35868. }
  35869. }
  35870. this._uniformBuffer.dispose();
  35871. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35872. if (forceDisposeEffect && this._effect) {
  35873. if (!this.storeEffectOnSubMeshes) {
  35874. this._scene.getEngine()._releaseEffect(this._effect);
  35875. }
  35876. this._effect = null;
  35877. }
  35878. // Callback
  35879. this.onDisposeObservable.notifyObservers(this);
  35880. this.onDisposeObservable.clear();
  35881. this.onBindObservable.clear();
  35882. this.onUnBindObservable.clear();
  35883. };
  35884. /**
  35885. * Serializes this material
  35886. * @returns the serialized material object
  35887. */
  35888. Material.prototype.serialize = function () {
  35889. return BABYLON.SerializationHelper.Serialize(this);
  35890. };
  35891. /**
  35892. * Creates a MultiMaterial from parsed MultiMaterial data.
  35893. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35894. * @param scene defines the hosting scene
  35895. * @returns a new MultiMaterial
  35896. */
  35897. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35898. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35899. multiMaterial.id = parsedMultiMaterial.id;
  35900. if (BABYLON.Tags) {
  35901. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35902. }
  35903. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35904. var subMatId = parsedMultiMaterial.materials[matIndex];
  35905. if (subMatId) {
  35906. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35907. }
  35908. else {
  35909. multiMaterial.subMaterials.push(null);
  35910. }
  35911. }
  35912. return multiMaterial;
  35913. };
  35914. /**
  35915. * Creates a material from parsed material data
  35916. * @param parsedMaterial defines parsed material data
  35917. * @param scene defines the hosting scene
  35918. * @param rootUrl defines the root URL to use to load textures
  35919. * @returns a new material
  35920. */
  35921. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35922. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35923. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35924. }
  35925. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35926. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35927. if (!BABYLON.LegacyPBRMaterial) {
  35928. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35929. return;
  35930. }
  35931. }
  35932. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35933. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35934. };
  35935. // Triangle views
  35936. Material._TriangleFillMode = 0;
  35937. Material._WireFrameFillMode = 1;
  35938. Material._PointFillMode = 2;
  35939. // Draw modes
  35940. Material._PointListDrawMode = 3;
  35941. Material._LineListDrawMode = 4;
  35942. Material._LineLoopDrawMode = 5;
  35943. Material._LineStripDrawMode = 6;
  35944. Material._TriangleStripDrawMode = 7;
  35945. Material._TriangleFanDrawMode = 8;
  35946. /**
  35947. * Stores the clock-wise side orientation
  35948. */
  35949. Material._ClockWiseSideOrientation = 0;
  35950. /**
  35951. * Stores the counter clock-wise side orientation
  35952. */
  35953. Material._CounterClockWiseSideOrientation = 1;
  35954. /**
  35955. * The dirty texture flag value
  35956. */
  35957. Material._TextureDirtyFlag = 1;
  35958. /**
  35959. * The dirty light flag value
  35960. */
  35961. Material._LightDirtyFlag = 2;
  35962. /**
  35963. * The dirty fresnel flag value
  35964. */
  35965. Material._FresnelDirtyFlag = 4;
  35966. /**
  35967. * The dirty attribute flag value
  35968. */
  35969. Material._AttributesDirtyFlag = 8;
  35970. /**
  35971. * The dirty misc flag value
  35972. */
  35973. Material._MiscDirtyFlag = 16;
  35974. __decorate([
  35975. BABYLON.serialize()
  35976. ], Material.prototype, "id", void 0);
  35977. __decorate([
  35978. BABYLON.serialize()
  35979. ], Material.prototype, "uniqueId", void 0);
  35980. __decorate([
  35981. BABYLON.serialize()
  35982. ], Material.prototype, "name", void 0);
  35983. __decorate([
  35984. BABYLON.serialize()
  35985. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35986. __decorate([
  35987. BABYLON.serialize()
  35988. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35989. __decorate([
  35990. BABYLON.serialize()
  35991. ], Material.prototype, "state", void 0);
  35992. __decorate([
  35993. BABYLON.serialize("alpha")
  35994. ], Material.prototype, "_alpha", void 0);
  35995. __decorate([
  35996. BABYLON.serialize("backFaceCulling")
  35997. ], Material.prototype, "_backFaceCulling", void 0);
  35998. __decorate([
  35999. BABYLON.serialize()
  36000. ], Material.prototype, "sideOrientation", void 0);
  36001. __decorate([
  36002. BABYLON.serialize("alphaMode")
  36003. ], Material.prototype, "_alphaMode", void 0);
  36004. __decorate([
  36005. BABYLON.serialize()
  36006. ], Material.prototype, "_needDepthPrePass", void 0);
  36007. __decorate([
  36008. BABYLON.serialize()
  36009. ], Material.prototype, "disableDepthWrite", void 0);
  36010. __decorate([
  36011. BABYLON.serialize()
  36012. ], Material.prototype, "forceDepthWrite", void 0);
  36013. __decorate([
  36014. BABYLON.serialize()
  36015. ], Material.prototype, "separateCullingPass", void 0);
  36016. __decorate([
  36017. BABYLON.serialize("fogEnabled")
  36018. ], Material.prototype, "_fogEnabled", void 0);
  36019. __decorate([
  36020. BABYLON.serialize()
  36021. ], Material.prototype, "pointSize", void 0);
  36022. __decorate([
  36023. BABYLON.serialize()
  36024. ], Material.prototype, "zOffset", void 0);
  36025. __decorate([
  36026. BABYLON.serialize()
  36027. ], Material.prototype, "wireframe", null);
  36028. __decorate([
  36029. BABYLON.serialize()
  36030. ], Material.prototype, "pointsCloud", null);
  36031. __decorate([
  36032. BABYLON.serialize()
  36033. ], Material.prototype, "fillMode", null);
  36034. return Material;
  36035. }());
  36036. BABYLON.Material = Material;
  36037. })(BABYLON || (BABYLON = {}));
  36038. //# sourceMappingURL=babylon.material.js.map
  36039. var BABYLON;
  36040. (function (BABYLON) {
  36041. var UniformBuffer = /** @class */ (function () {
  36042. /**
  36043. * Uniform buffer objects.
  36044. *
  36045. * Handles blocks of uniform on the GPU.
  36046. *
  36047. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36048. *
  36049. * For more information, please refer to :
  36050. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36051. */
  36052. function UniformBuffer(engine, data, dynamic) {
  36053. this._engine = engine;
  36054. this._noUBO = !engine.supportsUniformBuffers;
  36055. this._dynamic = dynamic;
  36056. this._data = data || [];
  36057. this._uniformLocations = {};
  36058. this._uniformSizes = {};
  36059. this._uniformLocationPointer = 0;
  36060. this._needSync = false;
  36061. if (this._noUBO) {
  36062. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36063. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36064. this.updateFloat = this._updateFloatForEffect;
  36065. this.updateFloat2 = this._updateFloat2ForEffect;
  36066. this.updateFloat3 = this._updateFloat3ForEffect;
  36067. this.updateFloat4 = this._updateFloat4ForEffect;
  36068. this.updateMatrix = this._updateMatrixForEffect;
  36069. this.updateVector3 = this._updateVector3ForEffect;
  36070. this.updateVector4 = this._updateVector4ForEffect;
  36071. this.updateColor3 = this._updateColor3ForEffect;
  36072. this.updateColor4 = this._updateColor4ForEffect;
  36073. }
  36074. else {
  36075. this._engine._uniformBuffers.push(this);
  36076. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36077. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36078. this.updateFloat = this._updateFloatForUniform;
  36079. this.updateFloat2 = this._updateFloat2ForUniform;
  36080. this.updateFloat3 = this._updateFloat3ForUniform;
  36081. this.updateFloat4 = this._updateFloat4ForUniform;
  36082. this.updateMatrix = this._updateMatrixForUniform;
  36083. this.updateVector3 = this._updateVector3ForUniform;
  36084. this.updateVector4 = this._updateVector4ForUniform;
  36085. this.updateColor3 = this._updateColor3ForUniform;
  36086. this.updateColor4 = this._updateColor4ForUniform;
  36087. }
  36088. }
  36089. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36090. // Properties
  36091. /**
  36092. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36093. * or just falling back on setUniformXXX calls.
  36094. */
  36095. get: function () {
  36096. return !this._noUBO;
  36097. },
  36098. enumerable: true,
  36099. configurable: true
  36100. });
  36101. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36102. /**
  36103. * Indicates if the WebGL underlying uniform buffer is in sync
  36104. * with the javascript cache data.
  36105. */
  36106. get: function () {
  36107. return !this._needSync;
  36108. },
  36109. enumerable: true,
  36110. configurable: true
  36111. });
  36112. /**
  36113. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36114. * Also, a dynamic UniformBuffer will disable cache verification and always
  36115. * update the underlying WebGL uniform buffer to the GPU.
  36116. */
  36117. UniformBuffer.prototype.isDynamic = function () {
  36118. return this._dynamic !== undefined;
  36119. };
  36120. /**
  36121. * The data cache on JS side.
  36122. */
  36123. UniformBuffer.prototype.getData = function () {
  36124. return this._bufferData;
  36125. };
  36126. /**
  36127. * The underlying WebGL Uniform buffer.
  36128. */
  36129. UniformBuffer.prototype.getBuffer = function () {
  36130. return this._buffer;
  36131. };
  36132. /**
  36133. * std140 layout specifies how to align data within an UBO structure.
  36134. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36135. * for specs.
  36136. */
  36137. UniformBuffer.prototype._fillAlignment = function (size) {
  36138. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36139. // and 4x4 matrices
  36140. // TODO : change if other types are used
  36141. var alignment;
  36142. if (size <= 2) {
  36143. alignment = size;
  36144. }
  36145. else {
  36146. alignment = 4;
  36147. }
  36148. if ((this._uniformLocationPointer % alignment) !== 0) {
  36149. var oldPointer = this._uniformLocationPointer;
  36150. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36151. var diff = this._uniformLocationPointer - oldPointer;
  36152. for (var i = 0; i < diff; i++) {
  36153. this._data.push(0);
  36154. }
  36155. }
  36156. };
  36157. /**
  36158. * Adds an uniform in the buffer.
  36159. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36160. * for the layout to be correct !
  36161. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36162. * @param {number|number[]} size Data size, or data directly.
  36163. */
  36164. UniformBuffer.prototype.addUniform = function (name, size) {
  36165. if (this._noUBO) {
  36166. return;
  36167. }
  36168. if (this._uniformLocations[name] !== undefined) {
  36169. // Already existing uniform
  36170. return;
  36171. }
  36172. // This function must be called in the order of the shader layout !
  36173. // size can be the size of the uniform, or data directly
  36174. var data;
  36175. if (size instanceof Array) {
  36176. data = size;
  36177. size = data.length;
  36178. }
  36179. else {
  36180. size = size;
  36181. data = [];
  36182. // Fill with zeros
  36183. for (var i = 0; i < size; i++) {
  36184. data.push(0);
  36185. }
  36186. }
  36187. this._fillAlignment(size);
  36188. this._uniformSizes[name] = size;
  36189. this._uniformLocations[name] = this._uniformLocationPointer;
  36190. this._uniformLocationPointer += size;
  36191. for (var i = 0; i < size; i++) {
  36192. this._data.push(data[i]);
  36193. }
  36194. this._needSync = true;
  36195. };
  36196. /**
  36197. * Wrapper for addUniform.
  36198. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36199. * @param {Matrix} mat A 4x4 matrix.
  36200. */
  36201. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36202. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36203. };
  36204. /**
  36205. * Wrapper for addUniform.
  36206. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36207. * @param {number} x
  36208. * @param {number} y
  36209. */
  36210. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36211. var temp = [x, y];
  36212. this.addUniform(name, temp);
  36213. };
  36214. /**
  36215. * Wrapper for addUniform.
  36216. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36217. * @param {number} x
  36218. * @param {number} y
  36219. * @param {number} z
  36220. */
  36221. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36222. var temp = [x, y, z];
  36223. this.addUniform(name, temp);
  36224. };
  36225. /**
  36226. * Wrapper for addUniform.
  36227. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36228. * @param {Color3} color
  36229. */
  36230. UniformBuffer.prototype.addColor3 = function (name, color) {
  36231. var temp = new Array();
  36232. color.toArray(temp);
  36233. this.addUniform(name, temp);
  36234. };
  36235. /**
  36236. * Wrapper for addUniform.
  36237. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36238. * @param {Color3} color
  36239. * @param {number} alpha
  36240. */
  36241. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36242. var temp = new Array();
  36243. color.toArray(temp);
  36244. temp.push(alpha);
  36245. this.addUniform(name, temp);
  36246. };
  36247. /**
  36248. * Wrapper for addUniform.
  36249. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36250. * @param {Vector3} vector
  36251. */
  36252. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36253. var temp = new Array();
  36254. vector.toArray(temp);
  36255. this.addUniform(name, temp);
  36256. };
  36257. /**
  36258. * Wrapper for addUniform.
  36259. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36260. */
  36261. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36262. this.addUniform(name, 12);
  36263. };
  36264. /**
  36265. * Wrapper for addUniform.
  36266. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36267. */
  36268. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36269. this.addUniform(name, 8);
  36270. };
  36271. /**
  36272. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36273. */
  36274. UniformBuffer.prototype.create = function () {
  36275. if (this._noUBO) {
  36276. return;
  36277. }
  36278. if (this._buffer) {
  36279. return; // nothing to do
  36280. }
  36281. // See spec, alignment must be filled as a vec4
  36282. this._fillAlignment(4);
  36283. this._bufferData = new Float32Array(this._data);
  36284. this._rebuild();
  36285. this._needSync = true;
  36286. };
  36287. UniformBuffer.prototype._rebuild = function () {
  36288. if (this._noUBO) {
  36289. return;
  36290. }
  36291. if (this._dynamic) {
  36292. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36293. }
  36294. else {
  36295. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36296. }
  36297. };
  36298. /**
  36299. * Updates the WebGL Uniform Buffer on the GPU.
  36300. * If the `dynamic` flag is set to true, no cache comparison is done.
  36301. * Otherwise, the buffer will be updated only if the cache differs.
  36302. */
  36303. UniformBuffer.prototype.update = function () {
  36304. if (!this._buffer) {
  36305. this.create();
  36306. return;
  36307. }
  36308. if (!this._dynamic && !this._needSync) {
  36309. return;
  36310. }
  36311. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36312. this._needSync = false;
  36313. };
  36314. /**
  36315. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36316. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36317. * @param {number[]|Float32Array} data Flattened data
  36318. * @param {number} size Size of the data.
  36319. */
  36320. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36321. var location = this._uniformLocations[uniformName];
  36322. if (location === undefined) {
  36323. if (this._buffer) {
  36324. // Cannot add an uniform if the buffer is already created
  36325. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36326. return;
  36327. }
  36328. this.addUniform(uniformName, size);
  36329. location = this._uniformLocations[uniformName];
  36330. }
  36331. if (!this._buffer) {
  36332. this.create();
  36333. }
  36334. if (!this._dynamic) {
  36335. // Cache for static uniform buffers
  36336. var changed = false;
  36337. for (var i = 0; i < size; i++) {
  36338. if (this._bufferData[location + i] !== data[i]) {
  36339. changed = true;
  36340. this._bufferData[location + i] = data[i];
  36341. }
  36342. }
  36343. this._needSync = this._needSync || changed;
  36344. }
  36345. else {
  36346. // No cache for dynamic
  36347. for (var i = 0; i < size; i++) {
  36348. this._bufferData[location + i] = data[i];
  36349. }
  36350. }
  36351. };
  36352. // Update methods
  36353. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36354. // To match std140, matrix must be realigned
  36355. for (var i = 0; i < 3; i++) {
  36356. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36357. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36358. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36359. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36360. }
  36361. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36362. };
  36363. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36364. this._currentEffect.setMatrix3x3(name, matrix);
  36365. };
  36366. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36367. this._currentEffect.setMatrix2x2(name, matrix);
  36368. };
  36369. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36370. // To match std140, matrix must be realigned
  36371. for (var i = 0; i < 2; i++) {
  36372. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36373. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36374. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36375. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36376. }
  36377. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36378. };
  36379. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36380. this._currentEffect.setFloat(name, x);
  36381. };
  36382. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36383. UniformBuffer._tempBuffer[0] = x;
  36384. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36385. };
  36386. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36387. if (suffix === void 0) { suffix = ""; }
  36388. this._currentEffect.setFloat2(name + suffix, x, y);
  36389. };
  36390. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36391. if (suffix === void 0) { suffix = ""; }
  36392. UniformBuffer._tempBuffer[0] = x;
  36393. UniformBuffer._tempBuffer[1] = y;
  36394. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36395. };
  36396. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36397. if (suffix === void 0) { suffix = ""; }
  36398. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36399. };
  36400. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36401. if (suffix === void 0) { suffix = ""; }
  36402. UniformBuffer._tempBuffer[0] = x;
  36403. UniformBuffer._tempBuffer[1] = y;
  36404. UniformBuffer._tempBuffer[2] = z;
  36405. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36406. };
  36407. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36408. if (suffix === void 0) { suffix = ""; }
  36409. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36410. };
  36411. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36412. if (suffix === void 0) { suffix = ""; }
  36413. UniformBuffer._tempBuffer[0] = x;
  36414. UniformBuffer._tempBuffer[1] = y;
  36415. UniformBuffer._tempBuffer[2] = z;
  36416. UniformBuffer._tempBuffer[3] = w;
  36417. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36418. };
  36419. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36420. this._currentEffect.setMatrix(name, mat);
  36421. };
  36422. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36423. this.updateUniform(name, mat.toArray(), 16);
  36424. };
  36425. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36426. this._currentEffect.setVector3(name, vector);
  36427. };
  36428. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36429. vector.toArray(UniformBuffer._tempBuffer);
  36430. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36431. };
  36432. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36433. this._currentEffect.setVector4(name, vector);
  36434. };
  36435. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36436. vector.toArray(UniformBuffer._tempBuffer);
  36437. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36438. };
  36439. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36440. if (suffix === void 0) { suffix = ""; }
  36441. this._currentEffect.setColor3(name + suffix, color);
  36442. };
  36443. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36444. if (suffix === void 0) { suffix = ""; }
  36445. color.toArray(UniformBuffer._tempBuffer);
  36446. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36447. };
  36448. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36449. if (suffix === void 0) { suffix = ""; }
  36450. this._currentEffect.setColor4(name + suffix, color, alpha);
  36451. };
  36452. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36453. if (suffix === void 0) { suffix = ""; }
  36454. color.toArray(UniformBuffer._tempBuffer);
  36455. UniformBuffer._tempBuffer[3] = alpha;
  36456. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36457. };
  36458. /**
  36459. * Sets a sampler uniform on the effect.
  36460. * @param {string} name Name of the sampler.
  36461. * @param {Texture} texture
  36462. */
  36463. UniformBuffer.prototype.setTexture = function (name, texture) {
  36464. this._currentEffect.setTexture(name, texture);
  36465. };
  36466. /**
  36467. * Directly updates the value of the uniform in the cache AND on the GPU.
  36468. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36469. * @param {number[]|Float32Array} data Flattened data
  36470. */
  36471. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36472. this.updateUniform(uniformName, data, data.length);
  36473. this.update();
  36474. };
  36475. /**
  36476. * Binds this uniform buffer to an effect.
  36477. * @param {Effect} effect
  36478. * @param {string} name Name of the uniform block in the shader.
  36479. */
  36480. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36481. this._currentEffect = effect;
  36482. if (this._noUBO || !this._buffer) {
  36483. return;
  36484. }
  36485. effect.bindUniformBuffer(this._buffer, name);
  36486. };
  36487. /**
  36488. * Disposes the uniform buffer.
  36489. */
  36490. UniformBuffer.prototype.dispose = function () {
  36491. if (this._noUBO) {
  36492. return;
  36493. }
  36494. var index = this._engine._uniformBuffers.indexOf(this);
  36495. if (index !== -1) {
  36496. this._engine._uniformBuffers.splice(index, 1);
  36497. }
  36498. if (!this._buffer) {
  36499. return;
  36500. }
  36501. if (this._engine._releaseBuffer(this._buffer)) {
  36502. this._buffer = null;
  36503. }
  36504. };
  36505. // Pool for avoiding memory leaks
  36506. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36507. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36508. return UniformBuffer;
  36509. }());
  36510. BABYLON.UniformBuffer = UniformBuffer;
  36511. })(BABYLON || (BABYLON = {}));
  36512. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36513. var BABYLON;
  36514. (function (BABYLON) {
  36515. /**
  36516. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36517. */
  36518. var VertexData = /** @class */ (function () {
  36519. function VertexData() {
  36520. }
  36521. /**
  36522. * Uses the passed data array to set the set the values for the specified kind of data
  36523. * @param data a linear array of floating numbers
  36524. * @param kind the type of data that is being set, eg positions, colors etc
  36525. */
  36526. VertexData.prototype.set = function (data, kind) {
  36527. switch (kind) {
  36528. case BABYLON.VertexBuffer.PositionKind:
  36529. this.positions = data;
  36530. break;
  36531. case BABYLON.VertexBuffer.NormalKind:
  36532. this.normals = data;
  36533. break;
  36534. case BABYLON.VertexBuffer.TangentKind:
  36535. this.tangents = data;
  36536. break;
  36537. case BABYLON.VertexBuffer.UVKind:
  36538. this.uvs = data;
  36539. break;
  36540. case BABYLON.VertexBuffer.UV2Kind:
  36541. this.uvs2 = data;
  36542. break;
  36543. case BABYLON.VertexBuffer.UV3Kind:
  36544. this.uvs3 = data;
  36545. break;
  36546. case BABYLON.VertexBuffer.UV4Kind:
  36547. this.uvs4 = data;
  36548. break;
  36549. case BABYLON.VertexBuffer.UV5Kind:
  36550. this.uvs5 = data;
  36551. break;
  36552. case BABYLON.VertexBuffer.UV6Kind:
  36553. this.uvs6 = data;
  36554. break;
  36555. case BABYLON.VertexBuffer.ColorKind:
  36556. this.colors = data;
  36557. break;
  36558. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36559. this.matricesIndices = data;
  36560. break;
  36561. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36562. this.matricesWeights = data;
  36563. break;
  36564. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36565. this.matricesIndicesExtra = data;
  36566. break;
  36567. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36568. this.matricesWeightsExtra = data;
  36569. break;
  36570. }
  36571. };
  36572. /**
  36573. * Associates the vertexData to the passed Mesh.
  36574. * Sets it as updatable or not (default `false`)
  36575. * @param mesh the mesh the vertexData is applied to
  36576. * @param updatable when used and having the value true allows new data to update the vertexData
  36577. * @returns the VertexData
  36578. */
  36579. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36580. this._applyTo(mesh, updatable);
  36581. return this;
  36582. };
  36583. /**
  36584. * Associates the vertexData to the passed Geometry.
  36585. * Sets it as updatable or not (default `false`)
  36586. * @param geometry the geometry the vertexData is applied to
  36587. * @param updatable when used and having the value true allows new data to update the vertexData
  36588. * @returns VertexData
  36589. */
  36590. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36591. this._applyTo(geometry, updatable);
  36592. return this;
  36593. };
  36594. /**
  36595. * Updates the associated mesh
  36596. * @param mesh the mesh to be updated
  36597. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36598. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36599. * @returns VertexData
  36600. */
  36601. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36602. this._update(mesh);
  36603. return this;
  36604. };
  36605. /**
  36606. * Updates the associated geometry
  36607. * @param geometry the geometry to be updated
  36608. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36609. * @param makeItUnique when true, and when and if position kind is updated, a new global geometry will be created from these positions and set to the mesh, optional with default false
  36610. * @returns VertexData.
  36611. */
  36612. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36613. this._update(geometry);
  36614. return this;
  36615. };
  36616. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36617. if (updatable === void 0) { updatable = false; }
  36618. if (this.positions) {
  36619. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36620. }
  36621. if (this.normals) {
  36622. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36623. }
  36624. if (this.tangents) {
  36625. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36626. }
  36627. if (this.uvs) {
  36628. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36629. }
  36630. if (this.uvs2) {
  36631. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36632. }
  36633. if (this.uvs3) {
  36634. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36635. }
  36636. if (this.uvs4) {
  36637. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36638. }
  36639. if (this.uvs5) {
  36640. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36641. }
  36642. if (this.uvs6) {
  36643. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36644. }
  36645. if (this.colors) {
  36646. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36647. }
  36648. if (this.matricesIndices) {
  36649. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36650. }
  36651. if (this.matricesWeights) {
  36652. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36653. }
  36654. if (this.matricesIndicesExtra) {
  36655. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36656. }
  36657. if (this.matricesWeightsExtra) {
  36658. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36659. }
  36660. if (this.indices) {
  36661. meshOrGeometry.setIndices(this.indices, null, updatable);
  36662. }
  36663. else {
  36664. meshOrGeometry.setIndices([], null);
  36665. }
  36666. return this;
  36667. };
  36668. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36669. if (this.positions) {
  36670. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36671. }
  36672. if (this.normals) {
  36673. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36674. }
  36675. if (this.tangents) {
  36676. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36677. }
  36678. if (this.uvs) {
  36679. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36680. }
  36681. if (this.uvs2) {
  36682. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36683. }
  36684. if (this.uvs3) {
  36685. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36686. }
  36687. if (this.uvs4) {
  36688. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36689. }
  36690. if (this.uvs5) {
  36691. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36692. }
  36693. if (this.uvs6) {
  36694. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36695. }
  36696. if (this.colors) {
  36697. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36698. }
  36699. if (this.matricesIndices) {
  36700. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36701. }
  36702. if (this.matricesWeights) {
  36703. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36704. }
  36705. if (this.matricesIndicesExtra) {
  36706. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36707. }
  36708. if (this.matricesWeightsExtra) {
  36709. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36710. }
  36711. if (this.indices) {
  36712. meshOrGeometry.setIndices(this.indices, null);
  36713. }
  36714. return this;
  36715. };
  36716. /**
  36717. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36718. * @param matrix the transforming matrix
  36719. * @returns the VertexData
  36720. */
  36721. VertexData.prototype.transform = function (matrix) {
  36722. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36723. var transformed = BABYLON.Vector3.Zero();
  36724. var index;
  36725. if (this.positions) {
  36726. var position = BABYLON.Vector3.Zero();
  36727. for (index = 0; index < this.positions.length; index += 3) {
  36728. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36729. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36730. this.positions[index] = transformed.x;
  36731. this.positions[index + 1] = transformed.y;
  36732. this.positions[index + 2] = transformed.z;
  36733. }
  36734. }
  36735. if (this.normals) {
  36736. var normal = BABYLON.Vector3.Zero();
  36737. for (index = 0; index < this.normals.length; index += 3) {
  36738. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36739. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36740. this.normals[index] = transformed.x;
  36741. this.normals[index + 1] = transformed.y;
  36742. this.normals[index + 2] = transformed.z;
  36743. }
  36744. }
  36745. if (this.tangents) {
  36746. var tangent = BABYLON.Vector4.Zero();
  36747. var tangentTransformed = BABYLON.Vector4.Zero();
  36748. for (index = 0; index < this.tangents.length; index += 4) {
  36749. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36750. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36751. this.tangents[index] = tangentTransformed.x;
  36752. this.tangents[index + 1] = tangentTransformed.y;
  36753. this.tangents[index + 2] = tangentTransformed.z;
  36754. this.tangents[index + 3] = tangentTransformed.w;
  36755. }
  36756. }
  36757. if (flip && this.indices) {
  36758. for (index = 0; index < this.indices.length; index += 3) {
  36759. var tmp = this.indices[index + 1];
  36760. this.indices[index + 1] = this.indices[index + 2];
  36761. this.indices[index + 2] = tmp;
  36762. }
  36763. }
  36764. return this;
  36765. };
  36766. /**
  36767. * Merges the passed VertexData into the current one
  36768. * @param other the VertexData to be merged into the current one
  36769. * @returns the modified VertexData
  36770. */
  36771. VertexData.prototype.merge = function (other) {
  36772. this._validate();
  36773. other._validate();
  36774. if (!this.normals !== !other.normals ||
  36775. !this.tangents !== !other.tangents ||
  36776. !this.uvs !== !other.uvs ||
  36777. !this.uvs2 !== !other.uvs2 ||
  36778. !this.uvs3 !== !other.uvs3 ||
  36779. !this.uvs4 !== !other.uvs4 ||
  36780. !this.uvs5 !== !other.uvs5 ||
  36781. !this.uvs6 !== !other.uvs6 ||
  36782. !this.colors !== !other.colors ||
  36783. !this.matricesIndices !== !other.matricesIndices ||
  36784. !this.matricesWeights !== !other.matricesWeights ||
  36785. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36786. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36787. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36788. }
  36789. if (other.indices) {
  36790. if (!this.indices) {
  36791. this.indices = [];
  36792. }
  36793. var offset = this.positions ? this.positions.length / 3 : 0;
  36794. for (var index = 0; index < other.indices.length; index++) {
  36795. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36796. this.indices.push(other.indices[index] + offset);
  36797. }
  36798. }
  36799. this.positions = this._mergeElement(this.positions, other.positions);
  36800. this.normals = this._mergeElement(this.normals, other.normals);
  36801. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36802. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36803. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36804. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36805. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36806. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36807. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36808. this.colors = this._mergeElement(this.colors, other.colors);
  36809. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36810. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36811. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36812. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36813. return this;
  36814. };
  36815. VertexData.prototype._mergeElement = function (source, other) {
  36816. if (!source) {
  36817. return other;
  36818. }
  36819. if (!other) {
  36820. return source;
  36821. }
  36822. var len = other.length + source.length;
  36823. var isSrcTypedArray = source instanceof Float32Array;
  36824. var isOthTypedArray = other instanceof Float32Array;
  36825. // use non-loop method when the source is Float32Array
  36826. if (isSrcTypedArray) {
  36827. var ret32 = new Float32Array(len);
  36828. ret32.set(source);
  36829. ret32.set(other, source.length);
  36830. return ret32;
  36831. // source is number[], when other is also use concat
  36832. }
  36833. else if (!isOthTypedArray) {
  36834. return source.concat(other);
  36835. // source is a number[], but other is a Float32Array, loop required
  36836. }
  36837. else {
  36838. var ret = source.slice(0); // copy source to a separate array
  36839. for (var i = 0, len = other.length; i < len; i++) {
  36840. ret.push(other[i]);
  36841. }
  36842. return ret;
  36843. }
  36844. };
  36845. VertexData.prototype._validate = function () {
  36846. if (!this.positions) {
  36847. throw new Error("Positions are required");
  36848. }
  36849. var getElementCount = function (kind, values) {
  36850. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36851. if ((values.length % stride) !== 0) {
  36852. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36853. }
  36854. return values.length / stride;
  36855. };
  36856. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36857. var validateElementCount = function (kind, values) {
  36858. var elementCount = getElementCount(kind, values);
  36859. if (elementCount !== positionsElementCount) {
  36860. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36861. }
  36862. };
  36863. if (this.normals)
  36864. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36865. if (this.tangents)
  36866. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36867. if (this.uvs)
  36868. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36869. if (this.uvs2)
  36870. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36871. if (this.uvs3)
  36872. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36873. if (this.uvs4)
  36874. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36875. if (this.uvs5)
  36876. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36877. if (this.uvs6)
  36878. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36879. if (this.colors)
  36880. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36881. if (this.matricesIndices)
  36882. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36883. if (this.matricesWeights)
  36884. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36885. if (this.matricesIndicesExtra)
  36886. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36887. if (this.matricesWeightsExtra)
  36888. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36889. };
  36890. /**
  36891. * Serializes the VertexData
  36892. * @returns a serialized object
  36893. */
  36894. VertexData.prototype.serialize = function () {
  36895. var serializationObject = this.serialize();
  36896. if (this.positions) {
  36897. serializationObject.positions = this.positions;
  36898. }
  36899. if (this.normals) {
  36900. serializationObject.normals = this.normals;
  36901. }
  36902. if (this.tangents) {
  36903. serializationObject.tangents = this.tangents;
  36904. }
  36905. if (this.uvs) {
  36906. serializationObject.uvs = this.uvs;
  36907. }
  36908. if (this.uvs2) {
  36909. serializationObject.uvs2 = this.uvs2;
  36910. }
  36911. if (this.uvs3) {
  36912. serializationObject.uvs3 = this.uvs3;
  36913. }
  36914. if (this.uvs4) {
  36915. serializationObject.uvs4 = this.uvs4;
  36916. }
  36917. if (this.uvs5) {
  36918. serializationObject.uvs5 = this.uvs5;
  36919. }
  36920. if (this.uvs6) {
  36921. serializationObject.uvs6 = this.uvs6;
  36922. }
  36923. if (this.colors) {
  36924. serializationObject.colors = this.colors;
  36925. }
  36926. if (this.matricesIndices) {
  36927. serializationObject.matricesIndices = this.matricesIndices;
  36928. serializationObject.matricesIndices._isExpanded = true;
  36929. }
  36930. if (this.matricesWeights) {
  36931. serializationObject.matricesWeights = this.matricesWeights;
  36932. }
  36933. if (this.matricesIndicesExtra) {
  36934. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36935. serializationObject.matricesIndicesExtra._isExpanded = true;
  36936. }
  36937. if (this.matricesWeightsExtra) {
  36938. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36939. }
  36940. serializationObject.indices = this.indices;
  36941. return serializationObject;
  36942. };
  36943. // Statics
  36944. /**
  36945. * Extracts the vertexData from a mesh
  36946. * @param mesh the mesh from which to extract the VertexData
  36947. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36948. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36949. * @returns the object VertexData associated to the passed mesh
  36950. */
  36951. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36952. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36953. };
  36954. /**
  36955. * Extracts the vertexData from the geometry
  36956. * @param geometry the geometry from which to extract the VertexData
  36957. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36958. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36959. * @returns the object VertexData associated to the passed mesh
  36960. */
  36961. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36962. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36963. };
  36964. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36965. var result = new VertexData();
  36966. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36967. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36968. }
  36969. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36970. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36971. }
  36972. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36973. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36974. }
  36975. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36976. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36977. }
  36978. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36979. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36980. }
  36981. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36982. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36983. }
  36984. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36985. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36986. }
  36987. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36988. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36989. }
  36990. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36991. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36992. }
  36993. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36994. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36995. }
  36996. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36997. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36998. }
  36999. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37000. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37001. }
  37002. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37003. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37004. }
  37005. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37006. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37007. }
  37008. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37009. return result;
  37010. };
  37011. /**
  37012. * Creates the VertexData for a Ribbon
  37013. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37014. * * pathArray array of paths, each of which an array of successive Vector3
  37015. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37016. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37017. * * offset a positive integer, only used when pathArray contains a single path (offset = 10 means the point 1 is joined to the point 11), default rounded half size of the pathArray length
  37018. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37019. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37020. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37021. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37022. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37023. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37024. * @returns the VertexData of the ribbon
  37025. */
  37026. VertexData.CreateRibbon = function (options) {
  37027. var pathArray = options.pathArray;
  37028. var closeArray = options.closeArray || false;
  37029. var closePath = options.closePath || false;
  37030. var invertUV = options.invertUV || false;
  37031. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37032. var offset = options.offset || defaultOffset;
  37033. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37034. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37035. var customUV = options.uvs;
  37036. var customColors = options.colors;
  37037. var positions = [];
  37038. var indices = [];
  37039. var normals = [];
  37040. var uvs = [];
  37041. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37042. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37043. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37044. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37045. var minlg; // minimal length among all paths from pathArray
  37046. var lg = []; // array of path lengths : nb of vertex per path
  37047. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37048. var p; // path iterator
  37049. var i; // point iterator
  37050. var j; // point iterator
  37051. // if single path in pathArray
  37052. if (pathArray.length < 2) {
  37053. var ar1 = [];
  37054. var ar2 = [];
  37055. for (i = 0; i < pathArray[0].length - offset; i++) {
  37056. ar1.push(pathArray[0][i]);
  37057. ar2.push(pathArray[0][i + offset]);
  37058. }
  37059. pathArray = [ar1, ar2];
  37060. }
  37061. // positions and horizontal distances (u)
  37062. var idc = 0;
  37063. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37064. var path;
  37065. var l;
  37066. minlg = pathArray[0].length;
  37067. var vectlg;
  37068. var dist;
  37069. for (p = 0; p < pathArray.length; p++) {
  37070. uTotalDistance[p] = 0;
  37071. us[p] = [0];
  37072. path = pathArray[p];
  37073. l = path.length;
  37074. minlg = (minlg < l) ? minlg : l;
  37075. j = 0;
  37076. while (j < l) {
  37077. positions.push(path[j].x, path[j].y, path[j].z);
  37078. if (j > 0) {
  37079. vectlg = path[j].subtract(path[j - 1]).length();
  37080. dist = vectlg + uTotalDistance[p];
  37081. us[p].push(dist);
  37082. uTotalDistance[p] = dist;
  37083. }
  37084. j++;
  37085. }
  37086. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37087. j--;
  37088. positions.push(path[0].x, path[0].y, path[0].z);
  37089. vectlg = path[j].subtract(path[0]).length();
  37090. dist = vectlg + uTotalDistance[p];
  37091. us[p].push(dist);
  37092. uTotalDistance[p] = dist;
  37093. }
  37094. lg[p] = l + closePathCorr;
  37095. idx[p] = idc;
  37096. idc += (l + closePathCorr);
  37097. }
  37098. // vertical distances (v)
  37099. var path1;
  37100. var path2;
  37101. var vertex1 = null;
  37102. var vertex2 = null;
  37103. for (i = 0; i < minlg + closePathCorr; i++) {
  37104. vTotalDistance[i] = 0;
  37105. vs[i] = [0];
  37106. for (p = 0; p < pathArray.length - 1; p++) {
  37107. path1 = pathArray[p];
  37108. path2 = pathArray[p + 1];
  37109. if (i === minlg) { // closePath
  37110. vertex1 = path1[0];
  37111. vertex2 = path2[0];
  37112. }
  37113. else {
  37114. vertex1 = path1[i];
  37115. vertex2 = path2[i];
  37116. }
  37117. vectlg = vertex2.subtract(vertex1).length();
  37118. dist = vectlg + vTotalDistance[i];
  37119. vs[i].push(dist);
  37120. vTotalDistance[i] = dist;
  37121. }
  37122. if (closeArray && vertex2 && vertex1) {
  37123. path1 = pathArray[p];
  37124. path2 = pathArray[0];
  37125. if (i === minlg) { // closePath
  37126. vertex2 = path2[0];
  37127. }
  37128. vectlg = vertex2.subtract(vertex1).length();
  37129. dist = vectlg + vTotalDistance[i];
  37130. vTotalDistance[i] = dist;
  37131. }
  37132. }
  37133. // uvs
  37134. var u;
  37135. var v;
  37136. if (customUV) {
  37137. for (p = 0; p < customUV.length; p++) {
  37138. uvs.push(customUV[p].x, customUV[p].y);
  37139. }
  37140. }
  37141. else {
  37142. for (p = 0; p < pathArray.length; p++) {
  37143. for (i = 0; i < minlg + closePathCorr; i++) {
  37144. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37145. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37146. if (invertUV) {
  37147. uvs.push(v, u);
  37148. }
  37149. else {
  37150. uvs.push(u, v);
  37151. }
  37152. }
  37153. }
  37154. }
  37155. // indices
  37156. p = 0; // path index
  37157. var pi = 0; // positions array index
  37158. var l1 = lg[p] - 1; // path1 length
  37159. var l2 = lg[p + 1] - 1; // path2 length
  37160. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37161. var shft = idx[1] - idx[0]; // shift
  37162. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37163. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37164. // 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
  37165. indices.push(pi, pi + shft, pi + 1);
  37166. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37167. pi += 1;
  37168. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37169. p++;
  37170. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37171. shft = idx[0] - idx[p];
  37172. l1 = lg[p] - 1;
  37173. l2 = lg[0] - 1;
  37174. }
  37175. else {
  37176. shft = idx[p + 1] - idx[p];
  37177. l1 = lg[p] - 1;
  37178. l2 = lg[p + 1] - 1;
  37179. }
  37180. pi = idx[p];
  37181. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37182. }
  37183. }
  37184. // normals
  37185. VertexData.ComputeNormals(positions, indices, normals);
  37186. if (closePath) { // update both the first and last vertex normals to their average value
  37187. var indexFirst = 0;
  37188. var indexLast = 0;
  37189. for (p = 0; p < pathArray.length; p++) {
  37190. indexFirst = idx[p] * 3;
  37191. if (p + 1 < pathArray.length) {
  37192. indexLast = (idx[p + 1] - 1) * 3;
  37193. }
  37194. else {
  37195. indexLast = normals.length - 3;
  37196. }
  37197. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37198. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37199. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37200. normals[indexLast] = normals[indexFirst];
  37201. normals[indexLast + 1] = normals[indexFirst + 1];
  37202. normals[indexLast + 2] = normals[indexFirst + 2];
  37203. }
  37204. }
  37205. // sides
  37206. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37207. // Colors
  37208. var colors = null;
  37209. if (customColors) {
  37210. colors = new Float32Array(customColors.length * 4);
  37211. for (var c = 0; c < customColors.length; c++) {
  37212. colors[c * 4] = customColors[c].r;
  37213. colors[c * 4 + 1] = customColors[c].g;
  37214. colors[c * 4 + 2] = customColors[c].b;
  37215. colors[c * 4 + 3] = customColors[c].a;
  37216. }
  37217. }
  37218. // Result
  37219. var vertexData = new VertexData();
  37220. var positions32 = new Float32Array(positions);
  37221. var normals32 = new Float32Array(normals);
  37222. var uvs32 = new Float32Array(uvs);
  37223. vertexData.indices = indices;
  37224. vertexData.positions = positions32;
  37225. vertexData.normals = normals32;
  37226. vertexData.uvs = uvs32;
  37227. if (colors) {
  37228. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37229. }
  37230. if (closePath) {
  37231. vertexData._idx = idx;
  37232. }
  37233. return vertexData;
  37234. };
  37235. /**
  37236. * Creates the VertexData for a box
  37237. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37238. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37239. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37240. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37241. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37242. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37243. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37244. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37245. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37246. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37247. * @returns the VertexData of the box
  37248. */
  37249. VertexData.CreateBox = function (options) {
  37250. var normalsSource = [
  37251. new BABYLON.Vector3(0, 0, 1),
  37252. new BABYLON.Vector3(0, 0, -1),
  37253. new BABYLON.Vector3(1, 0, 0),
  37254. new BABYLON.Vector3(-1, 0, 0),
  37255. new BABYLON.Vector3(0, 1, 0),
  37256. new BABYLON.Vector3(0, -1, 0)
  37257. ];
  37258. var indices = [];
  37259. var positions = [];
  37260. var normals = [];
  37261. var uvs = [];
  37262. var width = options.width || options.size || 1;
  37263. var height = options.height || options.size || 1;
  37264. var depth = options.depth || options.size || 1;
  37265. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37266. var faceUV = options.faceUV || new Array(6);
  37267. var faceColors = options.faceColors;
  37268. var colors = [];
  37269. // default face colors and UV if undefined
  37270. for (var f = 0; f < 6; f++) {
  37271. if (faceUV[f] === undefined) {
  37272. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37273. }
  37274. if (faceColors && faceColors[f] === undefined) {
  37275. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37276. }
  37277. }
  37278. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37279. // Create each face in turn.
  37280. for (var index = 0; index < normalsSource.length; index++) {
  37281. var normal = normalsSource[index];
  37282. // Get two vectors perpendicular to the face normal and to each other.
  37283. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37284. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37285. // Six indices (two triangles) per face.
  37286. var verticesLength = positions.length / 3;
  37287. indices.push(verticesLength);
  37288. indices.push(verticesLength + 1);
  37289. indices.push(verticesLength + 2);
  37290. indices.push(verticesLength);
  37291. indices.push(verticesLength + 2);
  37292. indices.push(verticesLength + 3);
  37293. // Four vertices per face.
  37294. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37295. positions.push(vertex.x, vertex.y, vertex.z);
  37296. normals.push(normal.x, normal.y, normal.z);
  37297. uvs.push(faceUV[index].z, faceUV[index].w);
  37298. if (faceColors) {
  37299. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37300. }
  37301. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37302. positions.push(vertex.x, vertex.y, vertex.z);
  37303. normals.push(normal.x, normal.y, normal.z);
  37304. uvs.push(faceUV[index].x, faceUV[index].w);
  37305. if (faceColors) {
  37306. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37307. }
  37308. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37309. positions.push(vertex.x, vertex.y, vertex.z);
  37310. normals.push(normal.x, normal.y, normal.z);
  37311. uvs.push(faceUV[index].x, faceUV[index].y);
  37312. if (faceColors) {
  37313. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37314. }
  37315. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37316. positions.push(vertex.x, vertex.y, vertex.z);
  37317. normals.push(normal.x, normal.y, normal.z);
  37318. uvs.push(faceUV[index].z, faceUV[index].y);
  37319. if (faceColors) {
  37320. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37321. }
  37322. }
  37323. // sides
  37324. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37325. // Result
  37326. var vertexData = new VertexData();
  37327. vertexData.indices = indices;
  37328. vertexData.positions = positions;
  37329. vertexData.normals = normals;
  37330. vertexData.uvs = uvs;
  37331. if (faceColors) {
  37332. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37333. vertexData.colors = totalColors;
  37334. }
  37335. return vertexData;
  37336. };
  37337. /**
  37338. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37339. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37340. * * segments sets the number of horizontal strips optional, default 32
  37341. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37342. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37343. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37344. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37345. * * arc a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the circumference (latitude) given by the arc value, optional, default 1
  37346. * * slice a number from 0 to 1, to create an unclosed ellipsoid based on the fraction of the height (latitude) given by the arc value, optional, default 1
  37347. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37348. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37349. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37350. * @returns the VertexData of the ellipsoid
  37351. */
  37352. VertexData.CreateSphere = function (options) {
  37353. var segments = options.segments || 32;
  37354. var diameterX = options.diameterX || options.diameter || 1;
  37355. var diameterY = options.diameterY || options.diameter || 1;
  37356. var diameterZ = options.diameterZ || options.diameter || 1;
  37357. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37358. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37359. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37360. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37361. var totalZRotationSteps = 2 + segments;
  37362. var totalYRotationSteps = 2 * totalZRotationSteps;
  37363. var indices = [];
  37364. var positions = [];
  37365. var normals = [];
  37366. var uvs = [];
  37367. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37368. var normalizedZ = zRotationStep / totalZRotationSteps;
  37369. var angleZ = normalizedZ * Math.PI * slice;
  37370. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37371. var normalizedY = yRotationStep / totalYRotationSteps;
  37372. var angleY = normalizedY * Math.PI * 2 * arc;
  37373. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37374. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37375. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37376. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37377. var vertex = complete.multiply(radius);
  37378. var normal = complete.divide(radius).normalize();
  37379. positions.push(vertex.x, vertex.y, vertex.z);
  37380. normals.push(normal.x, normal.y, normal.z);
  37381. uvs.push(normalizedY, normalizedZ);
  37382. }
  37383. if (zRotationStep > 0) {
  37384. var verticesCount = positions.length / 3;
  37385. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37386. indices.push((firstIndex));
  37387. indices.push((firstIndex + 1));
  37388. indices.push(firstIndex + totalYRotationSteps + 1);
  37389. indices.push((firstIndex + totalYRotationSteps + 1));
  37390. indices.push((firstIndex + 1));
  37391. indices.push((firstIndex + totalYRotationSteps + 2));
  37392. }
  37393. }
  37394. }
  37395. // Sides
  37396. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37397. // Result
  37398. var vertexData = new VertexData();
  37399. vertexData.indices = indices;
  37400. vertexData.positions = positions;
  37401. vertexData.normals = normals;
  37402. vertexData.uvs = uvs;
  37403. return vertexData;
  37404. };
  37405. /**
  37406. * Creates the VertexData for a cylinder, cone or prism
  37407. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37408. * * height sets the height (y direction) of the cylinder, optional, default 2
  37409. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37410. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37411. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37412. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37413. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37414. * * arc a number from 0 to 1, to create an unclosed cylinder based on the fraction of the circumference given by the arc value, optional, default 1
  37415. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37416. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37417. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37418. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37419. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37420. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37421. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37422. * @returns the VertexData of the cylinder, cone or prism
  37423. */
  37424. VertexData.CreateCylinder = function (options) {
  37425. var height = options.height || 2;
  37426. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37427. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37428. var tessellation = options.tessellation || 24;
  37429. var subdivisions = options.subdivisions || 1;
  37430. var hasRings = options.hasRings ? true : false;
  37431. var enclose = options.enclose ? true : false;
  37432. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37433. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37434. var faceUV = options.faceUV || new Array(3);
  37435. var faceColors = options.faceColors;
  37436. // default face colors and UV if undefined
  37437. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37438. var ringNb = (hasRings) ? subdivisions : 1;
  37439. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37440. var f;
  37441. for (f = 0; f < surfaceNb; f++) {
  37442. if (faceColors && faceColors[f] === undefined) {
  37443. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37444. }
  37445. }
  37446. for (f = 0; f < surfaceNb; f++) {
  37447. if (faceUV && faceUV[f] === undefined) {
  37448. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37449. }
  37450. }
  37451. var indices = new Array();
  37452. var positions = new Array();
  37453. var normals = new Array();
  37454. var uvs = new Array();
  37455. var colors = new Array();
  37456. var angle_step = Math.PI * 2 * arc / tessellation;
  37457. var angle;
  37458. var h;
  37459. var radius;
  37460. var tan = (diameterBottom - diameterTop) / 2 / height;
  37461. var ringVertex = BABYLON.Vector3.Zero();
  37462. var ringNormal = BABYLON.Vector3.Zero();
  37463. var ringFirstVertex = BABYLON.Vector3.Zero();
  37464. var ringFirstNormal = BABYLON.Vector3.Zero();
  37465. var quadNormal = BABYLON.Vector3.Zero();
  37466. var Y = BABYLON.Axis.Y;
  37467. // positions, normals, uvs
  37468. var i;
  37469. var j;
  37470. var r;
  37471. var ringIdx = 1;
  37472. var s = 1; // surface index
  37473. var cs = 0;
  37474. var v = 0;
  37475. for (i = 0; i <= subdivisions; i++) {
  37476. h = i / subdivisions;
  37477. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37478. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37479. for (r = 0; r < ringIdx; r++) {
  37480. if (hasRings) {
  37481. s += r;
  37482. }
  37483. if (enclose) {
  37484. s += 2 * r;
  37485. }
  37486. for (j = 0; j <= tessellation; j++) {
  37487. angle = j * angle_step;
  37488. // position
  37489. ringVertex.x = Math.cos(-angle) * radius;
  37490. ringVertex.y = -height / 2 + h * height;
  37491. ringVertex.z = Math.sin(-angle) * radius;
  37492. // normal
  37493. if (diameterTop === 0 && i === subdivisions) {
  37494. // if no top cap, reuse former normals
  37495. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37496. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37497. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37498. }
  37499. else {
  37500. ringNormal.x = ringVertex.x;
  37501. ringNormal.z = ringVertex.z;
  37502. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37503. ringNormal.normalize();
  37504. }
  37505. // keep first ring vertex values for enclose
  37506. if (j === 0) {
  37507. ringFirstVertex.copyFrom(ringVertex);
  37508. ringFirstNormal.copyFrom(ringNormal);
  37509. }
  37510. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37511. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37512. if (hasRings) {
  37513. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37514. }
  37515. else {
  37516. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37517. }
  37518. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37519. if (faceColors) {
  37520. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37521. }
  37522. }
  37523. // if enclose, add four vertices and their dedicated normals
  37524. if (arc !== 1 && enclose) {
  37525. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37526. positions.push(0, ringVertex.y, 0);
  37527. positions.push(0, ringVertex.y, 0);
  37528. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37529. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37530. quadNormal.normalize();
  37531. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37532. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37533. quadNormal.normalize();
  37534. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37535. if (hasRings) {
  37536. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37537. }
  37538. else {
  37539. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37540. }
  37541. uvs.push(faceUV[s + 1].x, v);
  37542. uvs.push(faceUV[s + 1].z, v);
  37543. if (hasRings) {
  37544. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37545. }
  37546. else {
  37547. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37548. }
  37549. uvs.push(faceUV[s + 2].x, v);
  37550. uvs.push(faceUV[s + 2].z, v);
  37551. if (faceColors) {
  37552. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37553. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37554. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37555. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37556. }
  37557. }
  37558. if (cs !== s) {
  37559. cs = s;
  37560. }
  37561. }
  37562. }
  37563. // indices
  37564. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37565. var s;
  37566. i = 0;
  37567. for (s = 0; s < subdivisions; s++) {
  37568. var i0 = 0;
  37569. var i1 = 0;
  37570. var i2 = 0;
  37571. var i3 = 0;
  37572. for (j = 0; j < tessellation; j++) {
  37573. i0 = i * (e + 1) + j;
  37574. i1 = (i + 1) * (e + 1) + j;
  37575. i2 = i * (e + 1) + (j + 1);
  37576. i3 = (i + 1) * (e + 1) + (j + 1);
  37577. indices.push(i0, i1, i2);
  37578. indices.push(i3, i2, i1);
  37579. }
  37580. if (arc !== 1 && enclose) { // if enclose, add two quads
  37581. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37582. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37583. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37584. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37585. }
  37586. i = (hasRings) ? (i + 2) : (i + 1);
  37587. }
  37588. // Caps
  37589. var createCylinderCap = function (isTop) {
  37590. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37591. if (radius === 0) {
  37592. return;
  37593. }
  37594. // Cap positions, normals & uvs
  37595. var angle;
  37596. var circleVector;
  37597. var i;
  37598. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37599. var c = null;
  37600. if (faceColors) {
  37601. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37602. }
  37603. // cap center
  37604. var vbase = positions.length / 3;
  37605. var offset = isTop ? height / 2 : -height / 2;
  37606. var center = new BABYLON.Vector3(0, offset, 0);
  37607. positions.push(center.x, center.y, center.z);
  37608. normals.push(0, isTop ? 1 : -1, 0);
  37609. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37610. if (c) {
  37611. colors.push(c.r, c.g, c.b, c.a);
  37612. }
  37613. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37614. for (i = 0; i <= tessellation; i++) {
  37615. angle = Math.PI * 2 * i * arc / tessellation;
  37616. var cos = Math.cos(-angle);
  37617. var sin = Math.sin(-angle);
  37618. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37619. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37620. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37621. normals.push(0, isTop ? 1 : -1, 0);
  37622. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37623. if (c) {
  37624. colors.push(c.r, c.g, c.b, c.a);
  37625. }
  37626. }
  37627. // Cap indices
  37628. for (i = 0; i < tessellation; i++) {
  37629. if (!isTop) {
  37630. indices.push(vbase);
  37631. indices.push(vbase + (i + 1));
  37632. indices.push(vbase + (i + 2));
  37633. }
  37634. else {
  37635. indices.push(vbase);
  37636. indices.push(vbase + (i + 2));
  37637. indices.push(vbase + (i + 1));
  37638. }
  37639. }
  37640. };
  37641. // add caps to geometry
  37642. createCylinderCap(false);
  37643. createCylinderCap(true);
  37644. // Sides
  37645. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37646. var vertexData = new VertexData();
  37647. vertexData.indices = indices;
  37648. vertexData.positions = positions;
  37649. vertexData.normals = normals;
  37650. vertexData.uvs = uvs;
  37651. if (faceColors) {
  37652. vertexData.colors = colors;
  37653. }
  37654. return vertexData;
  37655. };
  37656. /**
  37657. * Creates the VertexData for a torus
  37658. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37659. * * diameter the diameter of the torus, optional default 1
  37660. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37661. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37662. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37663. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37664. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37665. * @returns the VertexData of the torus
  37666. */
  37667. VertexData.CreateTorus = function (options) {
  37668. var indices = [];
  37669. var positions = [];
  37670. var normals = [];
  37671. var uvs = [];
  37672. var diameter = options.diameter || 1;
  37673. var thickness = options.thickness || 0.5;
  37674. var tessellation = options.tessellation || 16;
  37675. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37676. var stride = tessellation + 1;
  37677. for (var i = 0; i <= tessellation; i++) {
  37678. var u = i / tessellation;
  37679. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37680. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37681. for (var j = 0; j <= tessellation; j++) {
  37682. var v = 1 - j / tessellation;
  37683. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37684. var dx = Math.cos(innerAngle);
  37685. var dy = Math.sin(innerAngle);
  37686. // Create a vertex.
  37687. var normal = new BABYLON.Vector3(dx, dy, 0);
  37688. var position = normal.scale(thickness / 2);
  37689. var textureCoordinate = new BABYLON.Vector2(u, v);
  37690. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37691. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37692. positions.push(position.x, position.y, position.z);
  37693. normals.push(normal.x, normal.y, normal.z);
  37694. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37695. // And create indices for two triangles.
  37696. var nextI = (i + 1) % stride;
  37697. var nextJ = (j + 1) % stride;
  37698. indices.push(i * stride + j);
  37699. indices.push(i * stride + nextJ);
  37700. indices.push(nextI * stride + j);
  37701. indices.push(i * stride + nextJ);
  37702. indices.push(nextI * stride + nextJ);
  37703. indices.push(nextI * stride + j);
  37704. }
  37705. }
  37706. // Sides
  37707. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37708. // Result
  37709. var vertexData = new VertexData();
  37710. vertexData.indices = indices;
  37711. vertexData.positions = positions;
  37712. vertexData.normals = normals;
  37713. vertexData.uvs = uvs;
  37714. return vertexData;
  37715. };
  37716. /**
  37717. * Creates the VertexData of the LineSystem
  37718. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37719. * - lines an array of lines, each line being an array of successive Vector3
  37720. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37721. * @returns the VertexData of the LineSystem
  37722. */
  37723. VertexData.CreateLineSystem = function (options) {
  37724. var indices = [];
  37725. var positions = [];
  37726. var lines = options.lines;
  37727. var colors = options.colors;
  37728. var vertexColors = [];
  37729. var idx = 0;
  37730. for (var l = 0; l < lines.length; l++) {
  37731. var points = lines[l];
  37732. for (var index = 0; index < points.length; index++) {
  37733. positions.push(points[index].x, points[index].y, points[index].z);
  37734. if (colors) {
  37735. var color = colors[l];
  37736. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37737. }
  37738. if (index > 0) {
  37739. indices.push(idx - 1);
  37740. indices.push(idx);
  37741. }
  37742. idx++;
  37743. }
  37744. }
  37745. var vertexData = new VertexData();
  37746. vertexData.indices = indices;
  37747. vertexData.positions = positions;
  37748. if (colors) {
  37749. vertexData.colors = vertexColors;
  37750. }
  37751. return vertexData;
  37752. };
  37753. /**
  37754. * Create the VertexData for a DashedLines
  37755. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37756. * - points an array successive Vector3
  37757. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37758. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37759. * - dashNb the intended total number of dashes, optional, default 200
  37760. * @returns the VertexData for the DashedLines
  37761. */
  37762. VertexData.CreateDashedLines = function (options) {
  37763. var dashSize = options.dashSize || 3;
  37764. var gapSize = options.gapSize || 1;
  37765. var dashNb = options.dashNb || 200;
  37766. var points = options.points;
  37767. var positions = new Array();
  37768. var indices = new Array();
  37769. var curvect = BABYLON.Vector3.Zero();
  37770. var lg = 0;
  37771. var nb = 0;
  37772. var shft = 0;
  37773. var dashshft = 0;
  37774. var curshft = 0;
  37775. var idx = 0;
  37776. var i = 0;
  37777. for (i = 0; i < points.length - 1; i++) {
  37778. points[i + 1].subtractToRef(points[i], curvect);
  37779. lg += curvect.length();
  37780. }
  37781. shft = lg / dashNb;
  37782. dashshft = dashSize * shft / (dashSize + gapSize);
  37783. for (i = 0; i < points.length - 1; i++) {
  37784. points[i + 1].subtractToRef(points[i], curvect);
  37785. nb = Math.floor(curvect.length() / shft);
  37786. curvect.normalize();
  37787. for (var j = 0; j < nb; j++) {
  37788. curshft = shft * j;
  37789. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37790. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37791. indices.push(idx, idx + 1);
  37792. idx += 2;
  37793. }
  37794. }
  37795. // Result
  37796. var vertexData = new VertexData();
  37797. vertexData.positions = positions;
  37798. vertexData.indices = indices;
  37799. return vertexData;
  37800. };
  37801. /**
  37802. * Creates the VertexData for a Ground
  37803. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37804. * - width the width (x direction) of the ground, optional, default 1
  37805. * - height the height (z direction) of the ground, optional, default 1
  37806. * - subdivisions the number of subdivisions per side, optional, default 1
  37807. * @returns the VertexData of the Ground
  37808. */
  37809. VertexData.CreateGround = function (options) {
  37810. var indices = [];
  37811. var positions = [];
  37812. var normals = [];
  37813. var uvs = [];
  37814. var row, col;
  37815. var width = options.width || 1;
  37816. var height = options.height || 1;
  37817. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37818. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37819. for (row = 0; row <= subdivisionsY; row++) {
  37820. for (col = 0; col <= subdivisionsX; col++) {
  37821. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37822. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37823. positions.push(position.x, position.y, position.z);
  37824. normals.push(normal.x, normal.y, normal.z);
  37825. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37826. }
  37827. }
  37828. for (row = 0; row < subdivisionsY; row++) {
  37829. for (col = 0; col < subdivisionsX; col++) {
  37830. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37831. indices.push(col + 1 + row * (subdivisionsX + 1));
  37832. indices.push(col + row * (subdivisionsX + 1));
  37833. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37834. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37835. indices.push(col + row * (subdivisionsX + 1));
  37836. }
  37837. }
  37838. // Result
  37839. var vertexData = new VertexData();
  37840. vertexData.indices = indices;
  37841. vertexData.positions = positions;
  37842. vertexData.normals = normals;
  37843. vertexData.uvs = uvs;
  37844. return vertexData;
  37845. };
  37846. /**
  37847. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37848. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37849. * * xmin the ground minimum X coordinate, optional, default -1
  37850. * * zmin the ground minimum Z coordinate, optional, default -1
  37851. * * xmax the ground maximum X coordinate, optional, default 1
  37852. * * zmax the ground maximum Z coordinate, optional, default 1
  37853. * * subdivisions a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the ground width and height creating 'tiles', default {w: 6, h: 6}
  37854. * * precision a javascript object {w: positive integer, h: positive integer}, `w` and `h` are the numbers of subdivisions on the tile width and height, default {w: 2, h: 2}
  37855. * @returns the VertexData of the TiledGround
  37856. */
  37857. VertexData.CreateTiledGround = function (options) {
  37858. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37859. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37860. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37861. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37862. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37863. var precision = options.precision || { w: 1, h: 1 };
  37864. var indices = new Array();
  37865. var positions = new Array();
  37866. var normals = new Array();
  37867. var uvs = new Array();
  37868. var row, col, tileRow, tileCol;
  37869. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37870. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37871. precision.w = (precision.w < 1) ? 1 : precision.w;
  37872. precision.h = (precision.h < 1) ? 1 : precision.h;
  37873. var tileSize = {
  37874. 'w': (xmax - xmin) / subdivisions.w,
  37875. 'h': (zmax - zmin) / subdivisions.h
  37876. };
  37877. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37878. // Indices
  37879. var base = positions.length / 3;
  37880. var rowLength = precision.w + 1;
  37881. for (row = 0; row < precision.h; row++) {
  37882. for (col = 0; col < precision.w; col++) {
  37883. var square = [
  37884. base + col + row * rowLength,
  37885. base + (col + 1) + row * rowLength,
  37886. base + (col + 1) + (row + 1) * rowLength,
  37887. base + col + (row + 1) * rowLength
  37888. ];
  37889. indices.push(square[1]);
  37890. indices.push(square[2]);
  37891. indices.push(square[3]);
  37892. indices.push(square[0]);
  37893. indices.push(square[1]);
  37894. indices.push(square[3]);
  37895. }
  37896. }
  37897. // Position, normals and uvs
  37898. var position = BABYLON.Vector3.Zero();
  37899. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37900. for (row = 0; row <= precision.h; row++) {
  37901. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37902. for (col = 0; col <= precision.w; col++) {
  37903. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37904. position.y = 0;
  37905. positions.push(position.x, position.y, position.z);
  37906. normals.push(normal.x, normal.y, normal.z);
  37907. uvs.push(col / precision.w, row / precision.h);
  37908. }
  37909. }
  37910. }
  37911. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37912. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37913. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37914. }
  37915. }
  37916. // Result
  37917. var vertexData = new VertexData();
  37918. vertexData.indices = indices;
  37919. vertexData.positions = positions;
  37920. vertexData.normals = normals;
  37921. vertexData.uvs = uvs;
  37922. return vertexData;
  37923. };
  37924. /**
  37925. * Creates the VertexData of the Ground designed from a heightmap
  37926. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37927. * * width the width (x direction) of the ground
  37928. * * height the height (z direction) of the ground
  37929. * * subdivisions the number of subdivisions per side
  37930. * * minHeight the minimum altitude on the ground, optional, default 0
  37931. * * maxHeight the maximum altitude on the ground, optional default 1
  37932. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37933. * * buffer the array holding the image color data
  37934. * * bufferWidth the width of image
  37935. * * bufferHeight the height of image
  37936. * @returns the VertexData of the Ground designed from a heightmap
  37937. */
  37938. VertexData.CreateGroundFromHeightMap = function (options) {
  37939. var indices = [];
  37940. var positions = [];
  37941. var normals = [];
  37942. var uvs = [];
  37943. var row, col;
  37944. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37945. // Vertices
  37946. for (row = 0; row <= options.subdivisions; row++) {
  37947. for (col = 0; col <= options.subdivisions; col++) {
  37948. 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));
  37949. // Compute height
  37950. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37951. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37952. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37953. var r = options.buffer[pos] / 255.0;
  37954. var g = options.buffer[pos + 1] / 255.0;
  37955. var b = options.buffer[pos + 2] / 255.0;
  37956. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37957. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37958. // Add vertex
  37959. positions.push(position.x, position.y, position.z);
  37960. normals.push(0, 0, 0);
  37961. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37962. }
  37963. }
  37964. // Indices
  37965. for (row = 0; row < options.subdivisions; row++) {
  37966. for (col = 0; col < options.subdivisions; col++) {
  37967. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37968. indices.push(col + 1 + row * (options.subdivisions + 1));
  37969. indices.push(col + row * (options.subdivisions + 1));
  37970. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37971. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37972. indices.push(col + row * (options.subdivisions + 1));
  37973. }
  37974. }
  37975. // Normals
  37976. VertexData.ComputeNormals(positions, indices, normals);
  37977. // Result
  37978. var vertexData = new VertexData();
  37979. vertexData.indices = indices;
  37980. vertexData.positions = positions;
  37981. vertexData.normals = normals;
  37982. vertexData.uvs = uvs;
  37983. return vertexData;
  37984. };
  37985. /**
  37986. * Creates the VertexData for a Plane
  37987. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37988. * * size sets the width and height of the plane to the value of size, optional default 1
  37989. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37990. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37991. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37992. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37993. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37994. * @returns the VertexData of the box
  37995. */
  37996. VertexData.CreatePlane = function (options) {
  37997. var indices = [];
  37998. var positions = [];
  37999. var normals = [];
  38000. var uvs = [];
  38001. var width = options.width || options.size || 1;
  38002. var height = options.height || options.size || 1;
  38003. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38004. // Vertices
  38005. var halfWidth = width / 2.0;
  38006. var halfHeight = height / 2.0;
  38007. positions.push(-halfWidth, -halfHeight, 0);
  38008. normals.push(0, 0, -1.0);
  38009. uvs.push(0.0, 0.0);
  38010. positions.push(halfWidth, -halfHeight, 0);
  38011. normals.push(0, 0, -1.0);
  38012. uvs.push(1.0, 0.0);
  38013. positions.push(halfWidth, halfHeight, 0);
  38014. normals.push(0, 0, -1.0);
  38015. uvs.push(1.0, 1.0);
  38016. positions.push(-halfWidth, halfHeight, 0);
  38017. normals.push(0, 0, -1.0);
  38018. uvs.push(0.0, 1.0);
  38019. // Indices
  38020. indices.push(0);
  38021. indices.push(1);
  38022. indices.push(2);
  38023. indices.push(0);
  38024. indices.push(2);
  38025. indices.push(3);
  38026. // Sides
  38027. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38028. // Result
  38029. var vertexData = new VertexData();
  38030. vertexData.indices = indices;
  38031. vertexData.positions = positions;
  38032. vertexData.normals = normals;
  38033. vertexData.uvs = uvs;
  38034. return vertexData;
  38035. };
  38036. /**
  38037. * Creates the VertexData of the Disc or regular Polygon
  38038. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38039. * * radius the radius of the disc, optional default 0.5
  38040. * * tessellation the number of polygon sides, optional, default 64
  38041. * * arc a number from 0 to 1, to create an unclosed polygon based on the fraction of the circumference given by the arc value, optional, default 1
  38042. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38043. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38044. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38045. * @returns the VertexData of the box
  38046. */
  38047. VertexData.CreateDisc = function (options) {
  38048. var positions = new Array();
  38049. var indices = new Array();
  38050. var normals = new Array();
  38051. var uvs = new Array();
  38052. var radius = options.radius || 0.5;
  38053. var tessellation = options.tessellation || 64;
  38054. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38055. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38056. // positions and uvs
  38057. positions.push(0, 0, 0); // disc center first
  38058. uvs.push(0.5, 0.5);
  38059. var theta = Math.PI * 2 * arc;
  38060. var step = theta / tessellation;
  38061. for (var a = 0; a < theta; a += step) {
  38062. var x = Math.cos(a);
  38063. var y = Math.sin(a);
  38064. var u = (x + 1) / 2;
  38065. var v = (1 - y) / 2;
  38066. positions.push(radius * x, radius * y, 0);
  38067. uvs.push(u, v);
  38068. }
  38069. if (arc === 1) {
  38070. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38071. uvs.push(uvs[2], uvs[3]);
  38072. }
  38073. //indices
  38074. var vertexNb = positions.length / 3;
  38075. for (var i = 1; i < vertexNb - 1; i++) {
  38076. indices.push(i + 1, 0, i);
  38077. }
  38078. // result
  38079. VertexData.ComputeNormals(positions, indices, normals);
  38080. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38081. var vertexData = new VertexData();
  38082. vertexData.indices = indices;
  38083. vertexData.positions = positions;
  38084. vertexData.normals = normals;
  38085. vertexData.uvs = uvs;
  38086. return vertexData;
  38087. };
  38088. /**
  38089. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38090. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38091. * @param polygon a mesh built from polygonTriangulation.build()
  38092. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38093. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38094. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38095. * @param frontUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38096. * @param backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38097. * @returns the VertexData of the Polygon
  38098. */
  38099. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38100. var faceUV = fUV || new Array(3);
  38101. var faceColors = fColors;
  38102. var colors = [];
  38103. // default face colors and UV if undefined
  38104. for (var f = 0; f < 3; f++) {
  38105. if (faceUV[f] === undefined) {
  38106. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38107. }
  38108. if (faceColors && faceColors[f] === undefined) {
  38109. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38110. }
  38111. }
  38112. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38113. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38114. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38115. var indices = polygon.getIndices();
  38116. // set face colours and textures
  38117. var idx = 0;
  38118. var face = 0;
  38119. for (var index = 0; index < normals.length; index += 3) {
  38120. //Edge Face no. 1
  38121. if (Math.abs(normals[index + 1]) < 0.001) {
  38122. face = 1;
  38123. }
  38124. //Top Face no. 0
  38125. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38126. face = 0;
  38127. }
  38128. //Bottom Face no. 2
  38129. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38130. face = 2;
  38131. }
  38132. idx = index / 3;
  38133. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38134. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38135. if (faceColors) {
  38136. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38137. }
  38138. }
  38139. // sides
  38140. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38141. // Result
  38142. var vertexData = new VertexData();
  38143. vertexData.indices = indices;
  38144. vertexData.positions = positions;
  38145. vertexData.normals = normals;
  38146. vertexData.uvs = uvs;
  38147. if (faceColors) {
  38148. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38149. vertexData.colors = totalColors;
  38150. }
  38151. return vertexData;
  38152. };
  38153. /**
  38154. * Creates the VertexData of the IcoSphere
  38155. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38156. * * radius the radius of the IcoSphere, optional default 1
  38157. * * radiusX allows stretching in the x direction, optional, default radius
  38158. * * radiusY allows stretching in the y direction, optional, default radius
  38159. * * radiusZ allows stretching in the z direction, optional, default radius
  38160. * * flat when true creates a flat shaded mesh, optional, default true
  38161. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38162. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38163. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38164. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38165. * @returns the VertexData of the IcoSphere
  38166. */
  38167. VertexData.CreateIcoSphere = function (options) {
  38168. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38169. var radius = options.radius || 1;
  38170. var flat = (options.flat === undefined) ? true : options.flat;
  38171. var subdivisions = options.subdivisions || 4;
  38172. var radiusX = options.radiusX || radius;
  38173. var radiusY = options.radiusY || radius;
  38174. var radiusZ = options.radiusZ || radius;
  38175. var t = (1 + Math.sqrt(5)) / 2;
  38176. // 12 vertex x,y,z
  38177. var ico_vertices = [
  38178. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38179. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38180. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38181. ];
  38182. // index of 3 vertex makes a face of icopshere
  38183. var ico_indices = [
  38184. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38185. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38186. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38187. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38188. ];
  38189. // vertex for uv have aliased position, not for UV
  38190. var vertices_unalias_id = [
  38191. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38192. // vertex alias
  38193. 0,
  38194. 2,
  38195. 3,
  38196. 3,
  38197. 3,
  38198. 4,
  38199. 7,
  38200. 8,
  38201. 9,
  38202. 9,
  38203. 10,
  38204. 11 // 23: B + 12
  38205. ];
  38206. // uv as integer step (not pixels !)
  38207. var ico_vertexuv = [
  38208. 5, 1, 3, 1, 6, 4, 0, 0,
  38209. 5, 3, 4, 2, 2, 2, 4, 0,
  38210. 2, 0, 1, 1, 6, 0, 6, 2,
  38211. // vertex alias (for same vertex on different faces)
  38212. 0, 4,
  38213. 3, 3,
  38214. 4, 4,
  38215. 3, 1,
  38216. 4, 2,
  38217. 4, 4,
  38218. 0, 2,
  38219. 1, 1,
  38220. 2, 2,
  38221. 3, 3,
  38222. 1, 3,
  38223. 2, 4 // 23: B + 12
  38224. ];
  38225. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38226. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38227. // First island of uv mapping
  38228. // v = 4h 3+ 2
  38229. // v = 3h 9+ 4
  38230. // v = 2h 9+ 5 B
  38231. // v = 1h 9 1 0
  38232. // v = 0h 3 8 7 A
  38233. // u = 0 1 2 3 4 5 6 *a
  38234. // Second island of uv mapping
  38235. // v = 4h 0+ B+ 4+
  38236. // v = 3h A+ 2+
  38237. // v = 2h 7+ 6 3+
  38238. // v = 1h 8+ 3+
  38239. // v = 0h
  38240. // u = 0 1 2 3 4 5 6 *a
  38241. // Face layout on texture UV mapping
  38242. // ============
  38243. // \ 4 /\ 16 / ======
  38244. // \ / \ / /\ 11 /
  38245. // \/ 7 \/ / \ /
  38246. // ======= / 10 \/
  38247. // /\ 17 /\ =======
  38248. // / \ / \ \ 15 /\
  38249. // / 8 \/ 12 \ \ / \
  38250. // ============ \/ 6 \
  38251. // \ 18 /\ ============
  38252. // \ / \ \ 5 /\ 0 /
  38253. // \/ 13 \ \ / \ /
  38254. // ======= \/ 1 \/
  38255. // =============
  38256. // /\ 19 /\ 2 /\
  38257. // / \ / \ / \
  38258. // / 14 \/ 9 \/ 3 \
  38259. // ===================
  38260. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38261. var ustep = 138 / 1024;
  38262. var vstep = 239 / 1024;
  38263. var uoffset = 60 / 1024;
  38264. var voffset = 26 / 1024;
  38265. // Second island should have margin, not to touch the first island
  38266. // avoid any borderline artefact in pixel rounding
  38267. var island_u_offset = -40 / 1024;
  38268. var island_v_offset = +20 / 1024;
  38269. // face is either island 0 or 1 :
  38270. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38271. var island = [
  38272. 0, 0, 0, 0, 1,
  38273. 0, 0, 1, 1, 0,
  38274. 0, 0, 1, 1, 0,
  38275. 0, 1, 1, 1, 0 // 15 - 19
  38276. ];
  38277. var indices = new Array();
  38278. var positions = new Array();
  38279. var normals = new Array();
  38280. var uvs = new Array();
  38281. var current_indice = 0;
  38282. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38283. var face_vertex_pos = new Array(3);
  38284. var face_vertex_uv = new Array(3);
  38285. var v012;
  38286. for (v012 = 0; v012 < 3; v012++) {
  38287. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38288. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38289. }
  38290. // create all with normals
  38291. for (var face = 0; face < 20; face++) {
  38292. // 3 vertex per face
  38293. for (v012 = 0; v012 < 3; v012++) {
  38294. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38295. var v_id = ico_indices[3 * face + v012];
  38296. // vertex have 3D position (x,y,z)
  38297. 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]);
  38298. // Normalize to get normal, then scale to radius
  38299. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38300. // uv Coordinates from vertex ID
  38301. 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);
  38302. }
  38303. // Subdivide the face (interpolate pos, norm, uv)
  38304. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38305. // - norm is linear interpolation of vertex corner normal
  38306. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38307. // - uv is linear interpolation
  38308. //
  38309. // Topology is as below for sub-divide by 2
  38310. // vertex shown as v0,v1,v2
  38311. // interp index is i1 to progress in range [v0,v1[
  38312. // interp index is i2 to progress in range [v0,v2[
  38313. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38314. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38315. //
  38316. //
  38317. // i2 v2
  38318. // ^ ^
  38319. // / / \
  38320. // / / \
  38321. // / / \
  38322. // / / (0,1) \
  38323. // / #---------\
  38324. // / / \ (0,0)'/ \
  38325. // / / \ / \
  38326. // / / \ / \
  38327. // / / (0,0) \ / (1,0) \
  38328. // / #---------#---------\
  38329. // v0 v1
  38330. //
  38331. // --------------------> i1
  38332. //
  38333. // interp of (i1,i2):
  38334. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38335. // along i1 : lerp(x0,x1, i1/(S-i2))
  38336. //
  38337. // centroid of triangle is needed to get help normal computation
  38338. // (c1,c2) are used for centroid location
  38339. var interp_vertex = function (i1, i2, c1, c2) {
  38340. // vertex is interpolated from
  38341. // - face_vertex_pos[0..2]
  38342. // - face_vertex_uv[0..2]
  38343. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38344. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38345. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38346. pos_interp.normalize();
  38347. var vertex_normal;
  38348. if (flat) {
  38349. // in flat mode, recalculate normal as face centroid normal
  38350. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38351. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38352. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38353. }
  38354. else {
  38355. // in smooth mode, recalculate normal from each single vertex position
  38356. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38357. }
  38358. // Vertex normal need correction due to X,Y,Z radius scaling
  38359. vertex_normal.x /= radiusX;
  38360. vertex_normal.y /= radiusY;
  38361. vertex_normal.z /= radiusZ;
  38362. vertex_normal.normalize();
  38363. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38364. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38365. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38366. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38367. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38368. uvs.push(uv_interp.x, uv_interp.y);
  38369. // push each vertex has member of a face
  38370. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38371. indices.push(current_indice);
  38372. current_indice++;
  38373. };
  38374. for (var i2 = 0; i2 < subdivisions; i2++) {
  38375. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38376. // face : (i1,i2) for /\ :
  38377. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38378. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38379. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38380. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38381. if (i1 + i2 + 1 < subdivisions) {
  38382. // face : (i1,i2)' for \/ :
  38383. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38384. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38385. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38386. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38387. }
  38388. }
  38389. }
  38390. }
  38391. // Sides
  38392. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38393. // Result
  38394. var vertexData = new VertexData();
  38395. vertexData.indices = indices;
  38396. vertexData.positions = positions;
  38397. vertexData.normals = normals;
  38398. vertexData.uvs = uvs;
  38399. return vertexData;
  38400. };
  38401. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38402. /**
  38403. * Creates the VertexData for a Polyhedron
  38404. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38405. * * type provided types are:
  38406. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38407. * * 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)
  38408. * * size the size of the IcoSphere, optional default 1
  38409. * * sizeX allows stretching in the x direction, optional, default size
  38410. * * sizeY allows stretching in the y direction, optional, default size
  38411. * * sizeZ allows stretching in the z direction, optional, default size
  38412. * * custom a number that overwrites the type to create from an extended set of polyhedron from https://www.babylonjs-playground.com/#21QRSK#15 with minimised editor
  38413. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38414. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38415. * * flat when true creates a flat shaded mesh, optional, default true
  38416. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38417. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38418. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38419. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38420. * @returns the VertexData of the Polyhedron
  38421. */
  38422. VertexData.CreatePolyhedron = function (options) {
  38423. // provided polyhedron types :
  38424. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38425. // 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)
  38426. var polyhedra = [];
  38427. 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]] };
  38428. 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]] };
  38429. polyhedra[2] = {
  38430. 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]],
  38431. 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]]
  38432. };
  38433. polyhedra[3] = {
  38434. 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]],
  38435. 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]]
  38436. };
  38437. polyhedra[4] = {
  38438. 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]],
  38439. 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]]
  38440. };
  38441. 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]] };
  38442. 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]] };
  38443. 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]] };
  38444. 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]] };
  38445. 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]] };
  38446. 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]] };
  38447. 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]] };
  38448. 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]] };
  38449. 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]] };
  38450. polyhedra[14] = {
  38451. 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]],
  38452. 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]]
  38453. };
  38454. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38455. var size = options.size;
  38456. var sizeX = options.sizeX || size || 1;
  38457. var sizeY = options.sizeY || size || 1;
  38458. var sizeZ = options.sizeZ || size || 1;
  38459. var data = options.custom || polyhedra[type];
  38460. var nbfaces = data.face.length;
  38461. var faceUV = options.faceUV || new Array(nbfaces);
  38462. var faceColors = options.faceColors;
  38463. var flat = (options.flat === undefined) ? true : options.flat;
  38464. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38465. var positions = new Array();
  38466. var indices = new Array();
  38467. var normals = new Array();
  38468. var uvs = new Array();
  38469. var colors = new Array();
  38470. var index = 0;
  38471. var faceIdx = 0; // face cursor in the array "indexes"
  38472. var indexes = new Array();
  38473. var i = 0;
  38474. var f = 0;
  38475. var u, v, ang, x, y, tmp;
  38476. // default face colors and UV if undefined
  38477. if (flat) {
  38478. for (f = 0; f < nbfaces; f++) {
  38479. if (faceColors && faceColors[f] === undefined) {
  38480. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38481. }
  38482. if (faceUV && faceUV[f] === undefined) {
  38483. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38484. }
  38485. }
  38486. }
  38487. if (!flat) {
  38488. for (i = 0; i < data.vertex.length; i++) {
  38489. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38490. uvs.push(0, 0);
  38491. }
  38492. for (f = 0; f < nbfaces; f++) {
  38493. for (i = 0; i < data.face[f].length - 2; i++) {
  38494. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38495. }
  38496. }
  38497. }
  38498. else {
  38499. for (f = 0; f < nbfaces; f++) {
  38500. var fl = data.face[f].length; // number of vertices of the current face
  38501. ang = 2 * Math.PI / fl;
  38502. x = 0.5 * Math.tan(ang / 2);
  38503. y = 0.5;
  38504. // positions, uvs, colors
  38505. for (i = 0; i < fl; i++) {
  38506. // positions
  38507. 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);
  38508. indexes.push(index);
  38509. index++;
  38510. // uvs
  38511. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38512. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38513. uvs.push(u, v);
  38514. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38515. y = x * Math.sin(ang) + y * Math.cos(ang);
  38516. x = tmp;
  38517. // colors
  38518. if (faceColors) {
  38519. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38520. }
  38521. }
  38522. // indices from indexes
  38523. for (i = 0; i < fl - 2; i++) {
  38524. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38525. }
  38526. faceIdx += fl;
  38527. }
  38528. }
  38529. VertexData.ComputeNormals(positions, indices, normals);
  38530. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38531. var vertexData = new VertexData();
  38532. vertexData.positions = positions;
  38533. vertexData.indices = indices;
  38534. vertexData.normals = normals;
  38535. vertexData.uvs = uvs;
  38536. if (faceColors && flat) {
  38537. vertexData.colors = colors;
  38538. }
  38539. return vertexData;
  38540. };
  38541. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38542. /**
  38543. * Creates the VertexData for a TorusKnot
  38544. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38545. * * radius the radius of the torus knot, optional, default 2
  38546. * * tube the thickness of the tube, optional, default 0.5
  38547. * * radialSegments the number of sides on each tube segments, optional, default 32
  38548. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38549. * * p the number of windings around the z axis, optional, default 2
  38550. * * q the number of windings around the x axis, optional, default 3
  38551. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38552. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  38553. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  38554. * @returns the VertexData of the Torus Knot
  38555. */
  38556. VertexData.CreateTorusKnot = function (options) {
  38557. var indices = new Array();
  38558. var positions = new Array();
  38559. var normals = new Array();
  38560. var uvs = new Array();
  38561. var radius = options.radius || 2;
  38562. var tube = options.tube || 0.5;
  38563. var radialSegments = options.radialSegments || 32;
  38564. var tubularSegments = options.tubularSegments || 32;
  38565. var p = options.p || 2;
  38566. var q = options.q || 3;
  38567. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38568. // Helper
  38569. var getPos = function (angle) {
  38570. var cu = Math.cos(angle);
  38571. var su = Math.sin(angle);
  38572. var quOverP = q / p * angle;
  38573. var cs = Math.cos(quOverP);
  38574. var tx = radius * (2 + cs) * 0.5 * cu;
  38575. var ty = radius * (2 + cs) * su * 0.5;
  38576. var tz = radius * Math.sin(quOverP) * 0.5;
  38577. return new BABYLON.Vector3(tx, ty, tz);
  38578. };
  38579. // Vertices
  38580. var i;
  38581. var j;
  38582. for (i = 0; i <= radialSegments; i++) {
  38583. var modI = i % radialSegments;
  38584. var u = modI / radialSegments * 2 * p * Math.PI;
  38585. var p1 = getPos(u);
  38586. var p2 = getPos(u + 0.01);
  38587. var tang = p2.subtract(p1);
  38588. var n = p2.add(p1);
  38589. var bitan = BABYLON.Vector3.Cross(tang, n);
  38590. n = BABYLON.Vector3.Cross(bitan, tang);
  38591. bitan.normalize();
  38592. n.normalize();
  38593. for (j = 0; j < tubularSegments; j++) {
  38594. var modJ = j % tubularSegments;
  38595. var v = modJ / tubularSegments * 2 * Math.PI;
  38596. var cx = -tube * Math.cos(v);
  38597. var cy = tube * Math.sin(v);
  38598. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38599. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38600. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38601. uvs.push(i / radialSegments);
  38602. uvs.push(j / tubularSegments);
  38603. }
  38604. }
  38605. for (i = 0; i < radialSegments; i++) {
  38606. for (j = 0; j < tubularSegments; j++) {
  38607. var jNext = (j + 1) % tubularSegments;
  38608. var a = i * tubularSegments + j;
  38609. var b = (i + 1) * tubularSegments + j;
  38610. var c = (i + 1) * tubularSegments + jNext;
  38611. var d = i * tubularSegments + jNext;
  38612. indices.push(d);
  38613. indices.push(b);
  38614. indices.push(a);
  38615. indices.push(d);
  38616. indices.push(c);
  38617. indices.push(b);
  38618. }
  38619. }
  38620. // Normals
  38621. VertexData.ComputeNormals(positions, indices, normals);
  38622. // Sides
  38623. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38624. // Result
  38625. var vertexData = new VertexData();
  38626. vertexData.indices = indices;
  38627. vertexData.positions = positions;
  38628. vertexData.normals = normals;
  38629. vertexData.uvs = uvs;
  38630. return vertexData;
  38631. };
  38632. // Tools
  38633. /**
  38634. * Compute normals for given positions and indices
  38635. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38636. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38637. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38638. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38639. * * facetNormals : optional array of facet normals (vector3)
  38640. * * facetPositions : optional array of facet positions (vector3)
  38641. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38642. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38643. * * bInfo : optional bounding info, required for facetPartitioning computation
  38644. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38645. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38646. * * useRightHandedSystem: optional boolean to for right handed system computation
  38647. * * depthSort : optional boolean to enable the facet depth sort computation
  38648. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38649. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38650. */
  38651. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38652. // temporary scalar variables
  38653. var index = 0; // facet index
  38654. var p1p2x = 0.0; // p1p2 vector x coordinate
  38655. var p1p2y = 0.0; // p1p2 vector y coordinate
  38656. var p1p2z = 0.0; // p1p2 vector z coordinate
  38657. var p3p2x = 0.0; // p3p2 vector x coordinate
  38658. var p3p2y = 0.0; // p3p2 vector y coordinate
  38659. var p3p2z = 0.0; // p3p2 vector z coordinate
  38660. var faceNormalx = 0.0; // facet normal x coordinate
  38661. var faceNormaly = 0.0; // facet normal y coordinate
  38662. var faceNormalz = 0.0; // facet normal z coordinate
  38663. var length = 0.0; // facet normal length before normalization
  38664. var v1x = 0; // vector1 x index in the positions array
  38665. var v1y = 0; // vector1 y index in the positions array
  38666. var v1z = 0; // vector1 z index in the positions array
  38667. var v2x = 0; // vector2 x index in the positions array
  38668. var v2y = 0; // vector2 y index in the positions array
  38669. var v2z = 0; // vector2 z index in the positions array
  38670. var v3x = 0; // vector3 x index in the positions array
  38671. var v3y = 0; // vector3 y index in the positions array
  38672. var v3z = 0; // vector3 z index in the positions array
  38673. var computeFacetNormals = false;
  38674. var computeFacetPositions = false;
  38675. var computeFacetPartitioning = false;
  38676. var computeDepthSort = false;
  38677. var faceNormalSign = 1;
  38678. var ratio = 0;
  38679. var distanceTo = null;
  38680. if (options) {
  38681. computeFacetNormals = (options.facetNormals) ? true : false;
  38682. computeFacetPositions = (options.facetPositions) ? true : false;
  38683. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38684. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38685. ratio = options.ratio || 0;
  38686. computeDepthSort = (options.depthSort) ? true : false;
  38687. distanceTo = (options.distanceTo);
  38688. if (computeDepthSort) {
  38689. if (distanceTo === undefined) {
  38690. distanceTo = BABYLON.Vector3.Zero();
  38691. }
  38692. var depthSortedFacets = options.depthSortedFacets;
  38693. }
  38694. }
  38695. // facetPartitioning reinit if needed
  38696. var xSubRatio = 0;
  38697. var ySubRatio = 0;
  38698. var zSubRatio = 0;
  38699. var subSq = 0;
  38700. if (computeFacetPartitioning && options && options.bbSize) {
  38701. var ox = 0; // X partitioning index for facet position
  38702. var oy = 0; // Y partinioning index for facet position
  38703. var oz = 0; // Z partinioning index for facet position
  38704. var b1x = 0; // X partitioning index for facet v1 vertex
  38705. var b1y = 0; // Y partitioning index for facet v1 vertex
  38706. var b1z = 0; // z partitioning index for facet v1 vertex
  38707. var b2x = 0; // X partitioning index for facet v2 vertex
  38708. var b2y = 0; // Y partitioning index for facet v2 vertex
  38709. var b2z = 0; // Z partitioning index for facet v2 vertex
  38710. var b3x = 0; // X partitioning index for facet v3 vertex
  38711. var b3y = 0; // Y partitioning index for facet v3 vertex
  38712. var b3z = 0; // Z partitioning index for facet v3 vertex
  38713. var block_idx_o = 0; // facet barycenter block index
  38714. var block_idx_v1 = 0; // v1 vertex block index
  38715. var block_idx_v2 = 0; // v2 vertex block index
  38716. var block_idx_v3 = 0; // v3 vertex block index
  38717. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38718. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38719. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38720. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38721. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38722. subSq = options.subDiv.max * options.subDiv.max;
  38723. options.facetPartitioning.length = 0;
  38724. }
  38725. // reset the normals
  38726. for (index = 0; index < positions.length; index++) {
  38727. normals[index] = 0.0;
  38728. }
  38729. // Loop : 1 indice triplet = 1 facet
  38730. var nbFaces = (indices.length / 3) | 0;
  38731. for (index = 0; index < nbFaces; index++) {
  38732. // get the indexes of the coordinates of each vertex of the facet
  38733. v1x = indices[index * 3] * 3;
  38734. v1y = v1x + 1;
  38735. v1z = v1x + 2;
  38736. v2x = indices[index * 3 + 1] * 3;
  38737. v2y = v2x + 1;
  38738. v2z = v2x + 2;
  38739. v3x = indices[index * 3 + 2] * 3;
  38740. v3y = v3x + 1;
  38741. v3z = v3x + 2;
  38742. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38743. p1p2y = positions[v1y] - positions[v2y];
  38744. p1p2z = positions[v1z] - positions[v2z];
  38745. p3p2x = positions[v3x] - positions[v2x];
  38746. p3p2y = positions[v3y] - positions[v2y];
  38747. p3p2z = positions[v3z] - positions[v2z];
  38748. // compute the face normal with the cross product
  38749. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38750. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38751. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38752. // normalize this normal and store it in the array facetData
  38753. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38754. length = (length === 0) ? 1.0 : length;
  38755. faceNormalx /= length;
  38756. faceNormaly /= length;
  38757. faceNormalz /= length;
  38758. if (computeFacetNormals && options) {
  38759. options.facetNormals[index].x = faceNormalx;
  38760. options.facetNormals[index].y = faceNormaly;
  38761. options.facetNormals[index].z = faceNormalz;
  38762. }
  38763. if (computeFacetPositions && options) {
  38764. // compute and the facet barycenter coordinates in the array facetPositions
  38765. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38766. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38767. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38768. }
  38769. if (computeFacetPartitioning && options) {
  38770. // store the facet indexes in arrays in the main facetPartitioning array :
  38771. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38772. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38773. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38774. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38775. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38776. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38777. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38778. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38779. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38780. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38781. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38782. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38783. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38784. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38785. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38786. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38787. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38788. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38789. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38790. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38791. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38792. // push each facet index in each block containing the vertex
  38793. options.facetPartitioning[block_idx_v1].push(index);
  38794. if (block_idx_v2 != block_idx_v1) {
  38795. options.facetPartitioning[block_idx_v2].push(index);
  38796. }
  38797. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38798. options.facetPartitioning[block_idx_v3].push(index);
  38799. }
  38800. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38801. options.facetPartitioning[block_idx_o].push(index);
  38802. }
  38803. }
  38804. if (computeDepthSort && options && options.facetPositions) {
  38805. var dsf = depthSortedFacets[index];
  38806. dsf.ind = index * 3;
  38807. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38808. }
  38809. // compute the normals anyway
  38810. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38811. normals[v1y] += faceNormaly;
  38812. normals[v1z] += faceNormalz;
  38813. normals[v2x] += faceNormalx;
  38814. normals[v2y] += faceNormaly;
  38815. normals[v2z] += faceNormalz;
  38816. normals[v3x] += faceNormalx;
  38817. normals[v3y] += faceNormaly;
  38818. normals[v3z] += faceNormalz;
  38819. }
  38820. // last normalization of each normal
  38821. for (index = 0; index < normals.length / 3; index++) {
  38822. faceNormalx = normals[index * 3];
  38823. faceNormaly = normals[index * 3 + 1];
  38824. faceNormalz = normals[index * 3 + 2];
  38825. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38826. length = (length === 0) ? 1.0 : length;
  38827. faceNormalx /= length;
  38828. faceNormaly /= length;
  38829. faceNormalz /= length;
  38830. normals[index * 3] = faceNormalx;
  38831. normals[index * 3 + 1] = faceNormaly;
  38832. normals[index * 3 + 2] = faceNormalz;
  38833. }
  38834. };
  38835. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38836. var li = indices.length;
  38837. var ln = normals.length;
  38838. var i;
  38839. var n;
  38840. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38841. switch (sideOrientation) {
  38842. case BABYLON.Mesh.FRONTSIDE:
  38843. // nothing changed
  38844. break;
  38845. case BABYLON.Mesh.BACKSIDE:
  38846. var tmp;
  38847. // indices
  38848. for (i = 0; i < li; i += 3) {
  38849. tmp = indices[i];
  38850. indices[i] = indices[i + 2];
  38851. indices[i + 2] = tmp;
  38852. }
  38853. // normals
  38854. for (n = 0; n < ln; n++) {
  38855. normals[n] = -normals[n];
  38856. }
  38857. break;
  38858. case BABYLON.Mesh.DOUBLESIDE:
  38859. // positions
  38860. var lp = positions.length;
  38861. var l = lp / 3;
  38862. for (var p = 0; p < lp; p++) {
  38863. positions[lp + p] = positions[p];
  38864. }
  38865. // indices
  38866. for (i = 0; i < li; i += 3) {
  38867. indices[i + li] = indices[i + 2] + l;
  38868. indices[i + 1 + li] = indices[i + 1] + l;
  38869. indices[i + 2 + li] = indices[i] + l;
  38870. }
  38871. // normals
  38872. for (n = 0; n < ln; n++) {
  38873. normals[ln + n] = -normals[n];
  38874. }
  38875. // uvs
  38876. var lu = uvs.length;
  38877. var u = 0;
  38878. for (u = 0; u < lu; u++) {
  38879. uvs[u + lu] = uvs[u];
  38880. }
  38881. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38882. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38883. u = 0;
  38884. for (i = 0; i < lu / 2; i++) {
  38885. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38886. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38887. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38888. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38889. u += 2;
  38890. }
  38891. break;
  38892. }
  38893. };
  38894. /**
  38895. * Applies VertexData created from the imported parameters to the geometry
  38896. * @param parsedVertexData the parsed data from an imported file
  38897. * @param geometry the geometry to apply the VertexData to
  38898. */
  38899. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38900. var vertexData = new VertexData();
  38901. // positions
  38902. var positions = parsedVertexData.positions;
  38903. if (positions) {
  38904. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38905. }
  38906. // normals
  38907. var normals = parsedVertexData.normals;
  38908. if (normals) {
  38909. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38910. }
  38911. // tangents
  38912. var tangents = parsedVertexData.tangents;
  38913. if (tangents) {
  38914. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38915. }
  38916. // uvs
  38917. var uvs = parsedVertexData.uvs;
  38918. if (uvs) {
  38919. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38920. }
  38921. // uv2s
  38922. var uv2s = parsedVertexData.uv2s;
  38923. if (uv2s) {
  38924. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38925. }
  38926. // uv3s
  38927. var uv3s = parsedVertexData.uv3s;
  38928. if (uv3s) {
  38929. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38930. }
  38931. // uv4s
  38932. var uv4s = parsedVertexData.uv4s;
  38933. if (uv4s) {
  38934. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38935. }
  38936. // uv5s
  38937. var uv5s = parsedVertexData.uv5s;
  38938. if (uv5s) {
  38939. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38940. }
  38941. // uv6s
  38942. var uv6s = parsedVertexData.uv6s;
  38943. if (uv6s) {
  38944. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38945. }
  38946. // colors
  38947. var colors = parsedVertexData.colors;
  38948. if (colors) {
  38949. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38950. }
  38951. // matricesIndices
  38952. var matricesIndices = parsedVertexData.matricesIndices;
  38953. if (matricesIndices) {
  38954. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38955. }
  38956. // matricesWeights
  38957. var matricesWeights = parsedVertexData.matricesWeights;
  38958. if (matricesWeights) {
  38959. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38960. }
  38961. // indices
  38962. var indices = parsedVertexData.indices;
  38963. if (indices) {
  38964. vertexData.indices = indices;
  38965. }
  38966. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38967. };
  38968. return VertexData;
  38969. }());
  38970. BABYLON.VertexData = VertexData;
  38971. })(BABYLON || (BABYLON = {}));
  38972. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38973. var BABYLON;
  38974. (function (BABYLON) {
  38975. /**
  38976. * Class used to store geometry data (vertex buffers + index buffer)
  38977. */
  38978. var Geometry = /** @class */ (function () {
  38979. /**
  38980. * Creates a new geometry
  38981. * @param id defines the unique ID
  38982. * @param scene defines the hosting scene
  38983. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38984. * @param updatable defines if geometry must be updatable (false by default)
  38985. * @param mesh defines the mesh that will be associated with the geometry
  38986. */
  38987. function Geometry(id, scene, vertexData, updatable, mesh) {
  38988. if (updatable === void 0) { updatable = false; }
  38989. if (mesh === void 0) { mesh = null; }
  38990. /**
  38991. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38992. */
  38993. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38994. this._totalVertices = 0;
  38995. this._isDisposed = false;
  38996. this._indexBufferIsUpdatable = false;
  38997. this.id = id;
  38998. this._engine = scene.getEngine();
  38999. this._meshes = [];
  39000. this._scene = scene;
  39001. //Init vertex buffer cache
  39002. this._vertexBuffers = {};
  39003. this._indices = [];
  39004. this._updatable = updatable;
  39005. // vertexData
  39006. if (vertexData) {
  39007. this.setAllVerticesData(vertexData, updatable);
  39008. }
  39009. else {
  39010. this._totalVertices = 0;
  39011. this._indices = [];
  39012. }
  39013. if (this._engine.getCaps().vertexArrayObject) {
  39014. this._vertexArrayObjects = {};
  39015. }
  39016. // applyToMesh
  39017. if (mesh) {
  39018. if (mesh.getClassName() === "LinesMesh") {
  39019. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39020. this._updateExtend();
  39021. }
  39022. this.applyToMesh(mesh);
  39023. mesh.computeWorldMatrix(true);
  39024. }
  39025. }
  39026. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39027. /**
  39028. * 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
  39029. */
  39030. get: function () {
  39031. return this._boundingBias;
  39032. },
  39033. /**
  39034. * 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
  39035. */
  39036. set: function (value) {
  39037. if (this._boundingBias && this._boundingBias.equals(value)) {
  39038. return;
  39039. }
  39040. this._boundingBias = value.clone();
  39041. this._updateBoundingInfo(true, null);
  39042. },
  39043. enumerable: true,
  39044. configurable: true
  39045. });
  39046. /**
  39047. * Static function used to attach a new empty geometry to a mesh
  39048. * @param mesh defines the mesh to attach the geometry to
  39049. * @returns the new {BABYLON.Geometry}
  39050. */
  39051. Geometry.CreateGeometryForMesh = function (mesh) {
  39052. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39053. geometry.applyToMesh(mesh);
  39054. return geometry;
  39055. };
  39056. Object.defineProperty(Geometry.prototype, "extend", {
  39057. /**
  39058. * Gets the current extend of the geometry
  39059. */
  39060. get: function () {
  39061. return this._extend;
  39062. },
  39063. enumerable: true,
  39064. configurable: true
  39065. });
  39066. /**
  39067. * Gets the hosting scene
  39068. * @returns the hosting {BABYLON.Scene}
  39069. */
  39070. Geometry.prototype.getScene = function () {
  39071. return this._scene;
  39072. };
  39073. /**
  39074. * Gets the hosting engine
  39075. * @returns the hosting {BABYLON.Engine}
  39076. */
  39077. Geometry.prototype.getEngine = function () {
  39078. return this._engine;
  39079. };
  39080. /**
  39081. * Defines if the geometry is ready to use
  39082. * @returns true if the geometry is ready to be used
  39083. */
  39084. Geometry.prototype.isReady = function () {
  39085. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39086. };
  39087. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39088. /**
  39089. * Gets a value indicating that the geometry should not be serialized
  39090. */
  39091. get: function () {
  39092. for (var index = 0; index < this._meshes.length; index++) {
  39093. if (!this._meshes[index].doNotSerialize) {
  39094. return false;
  39095. }
  39096. }
  39097. return true;
  39098. },
  39099. enumerable: true,
  39100. configurable: true
  39101. });
  39102. /** @hidden */
  39103. Geometry.prototype._rebuild = function () {
  39104. if (this._vertexArrayObjects) {
  39105. this._vertexArrayObjects = {};
  39106. }
  39107. // Index buffer
  39108. if (this._meshes.length !== 0 && this._indices) {
  39109. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39110. }
  39111. // Vertex buffers
  39112. for (var key in this._vertexBuffers) {
  39113. var vertexBuffer = this._vertexBuffers[key];
  39114. vertexBuffer._rebuild();
  39115. }
  39116. };
  39117. /**
  39118. * Affects all geometry data in one call
  39119. * @param vertexData defines the geometry data
  39120. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39121. */
  39122. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39123. vertexData.applyToGeometry(this, updatable);
  39124. this.notifyUpdate();
  39125. };
  39126. /**
  39127. * Set specific vertex data
  39128. * @param kind defines the data kind (Position, normal, etc...)
  39129. * @param data defines the vertex data to use
  39130. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39131. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39132. */
  39133. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39134. if (updatable === void 0) { updatable = false; }
  39135. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39136. this.setVerticesBuffer(buffer);
  39137. };
  39138. /**
  39139. * Removes a specific vertex data
  39140. * @param kind defines the data kind (Position, normal, etc...)
  39141. */
  39142. Geometry.prototype.removeVerticesData = function (kind) {
  39143. if (this._vertexBuffers[kind]) {
  39144. this._vertexBuffers[kind].dispose();
  39145. delete this._vertexBuffers[kind];
  39146. }
  39147. };
  39148. /**
  39149. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39150. * @param buffer defines the vertex buffer to use
  39151. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39152. */
  39153. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39154. if (totalVertices === void 0) { totalVertices = null; }
  39155. var kind = buffer.getKind();
  39156. if (this._vertexBuffers[kind]) {
  39157. this._vertexBuffers[kind].dispose();
  39158. }
  39159. this._vertexBuffers[kind] = buffer;
  39160. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39161. var data = buffer.getData();
  39162. if (totalVertices != null) {
  39163. this._totalVertices = totalVertices;
  39164. }
  39165. else {
  39166. if (data != null) {
  39167. this._totalVertices = data.length / (buffer.byteStride / 4);
  39168. }
  39169. }
  39170. this._updateExtend(data);
  39171. this._resetPointsArrayCache();
  39172. var meshes = this._meshes;
  39173. var numOfMeshes = meshes.length;
  39174. for (var index = 0; index < numOfMeshes; index++) {
  39175. var mesh = meshes[index];
  39176. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39177. mesh._createGlobalSubMesh(false);
  39178. mesh.computeWorldMatrix(true);
  39179. }
  39180. }
  39181. this.notifyUpdate(kind);
  39182. if (this._vertexArrayObjects) {
  39183. this._disposeVertexArrayObjects();
  39184. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39185. }
  39186. };
  39187. /**
  39188. * Update a specific vertex buffer
  39189. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39190. * It will do nothing if the buffer is not updatable
  39191. * @param kind defines the data kind (Position, normal, etc...)
  39192. * @param data defines the data to use
  39193. * @param offset defines the offset in the target buffer where to store the data
  39194. * @param useBytes set to true if the offset is in bytes
  39195. */
  39196. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39197. if (useBytes === void 0) { useBytes = false; }
  39198. var vertexBuffer = this.getVertexBuffer(kind);
  39199. if (!vertexBuffer) {
  39200. return;
  39201. }
  39202. vertexBuffer.updateDirectly(data, offset, useBytes);
  39203. this.notifyUpdate(kind);
  39204. };
  39205. /**
  39206. * Update a specific vertex buffer
  39207. * This function will create a new buffer if the current one is not updatable
  39208. * @param kind defines the data kind (Position, normal, etc...)
  39209. * @param data defines the data to use
  39210. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39211. */
  39212. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39213. if (updateExtends === void 0) { updateExtends = false; }
  39214. var vertexBuffer = this.getVertexBuffer(kind);
  39215. if (!vertexBuffer) {
  39216. return;
  39217. }
  39218. vertexBuffer.update(data);
  39219. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39220. this._updateBoundingInfo(updateExtends, data);
  39221. }
  39222. this.notifyUpdate(kind);
  39223. };
  39224. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39225. if (updateExtends) {
  39226. this._updateExtend(data);
  39227. }
  39228. var meshes = this._meshes;
  39229. var numOfMeshes = meshes.length;
  39230. this._resetPointsArrayCache();
  39231. for (var index = 0; index < numOfMeshes; index++) {
  39232. var mesh = meshes[index];
  39233. if (updateExtends) {
  39234. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39235. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39236. var subMesh = mesh.subMeshes[subIndex];
  39237. subMesh.refreshBoundingInfo();
  39238. }
  39239. }
  39240. }
  39241. };
  39242. /** @hidden */
  39243. Geometry.prototype._bind = function (effect, indexToBind) {
  39244. if (!effect) {
  39245. return;
  39246. }
  39247. if (indexToBind === undefined) {
  39248. indexToBind = this._indexBuffer;
  39249. }
  39250. var vbs = this.getVertexBuffers();
  39251. if (!vbs) {
  39252. return;
  39253. }
  39254. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39255. this._engine.bindBuffers(vbs, indexToBind, effect);
  39256. return;
  39257. }
  39258. // Using VAO
  39259. if (!this._vertexArrayObjects[effect.key]) {
  39260. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39261. }
  39262. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39263. };
  39264. /**
  39265. * Gets total number of vertices
  39266. * @returns the total number of vertices
  39267. */
  39268. Geometry.prototype.getTotalVertices = function () {
  39269. if (!this.isReady()) {
  39270. return 0;
  39271. }
  39272. return this._totalVertices;
  39273. };
  39274. /**
  39275. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39276. * @param kind defines the data kind (Position, normal, etc...)
  39277. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39278. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39279. * @returns a float array containing vertex data
  39280. */
  39281. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39282. var vertexBuffer = this.getVertexBuffer(kind);
  39283. if (!vertexBuffer) {
  39284. return null;
  39285. }
  39286. var data = vertexBuffer.getData();
  39287. if (!data) {
  39288. return null;
  39289. }
  39290. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39291. var count = this._totalVertices * vertexBuffer.getSize();
  39292. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39293. var copy_1 = new Array(count);
  39294. vertexBuffer.forEach(count, function (value, index) {
  39295. copy_1[index] = value;
  39296. });
  39297. return copy_1;
  39298. }
  39299. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39300. if (data instanceof Array) {
  39301. var offset = vertexBuffer.byteOffset / 4;
  39302. return BABYLON.Tools.Slice(data, offset, offset + count);
  39303. }
  39304. else if (data instanceof ArrayBuffer) {
  39305. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39306. }
  39307. else {
  39308. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39309. }
  39310. }
  39311. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39312. return BABYLON.Tools.Slice(data);
  39313. }
  39314. return data;
  39315. };
  39316. /**
  39317. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39318. * @param kind defines the data kind (Position, normal, etc...)
  39319. * @returns true if the vertex buffer with the specified kind is updatable
  39320. */
  39321. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39322. var vb = this._vertexBuffers[kind];
  39323. if (!vb) {
  39324. return false;
  39325. }
  39326. return vb.isUpdatable();
  39327. };
  39328. /**
  39329. * Gets a specific vertex buffer
  39330. * @param kind defines the data kind (Position, normal, etc...)
  39331. * @returns a {BABYLON.VertexBuffer}
  39332. */
  39333. Geometry.prototype.getVertexBuffer = function (kind) {
  39334. if (!this.isReady()) {
  39335. return null;
  39336. }
  39337. return this._vertexBuffers[kind];
  39338. };
  39339. /**
  39340. * Returns all vertex buffers
  39341. * @return an object holding all vertex buffers indexed by kind
  39342. */
  39343. Geometry.prototype.getVertexBuffers = function () {
  39344. if (!this.isReady()) {
  39345. return null;
  39346. }
  39347. return this._vertexBuffers;
  39348. };
  39349. /**
  39350. * Gets a boolean indicating if specific vertex buffer is present
  39351. * @param kind defines the data kind (Position, normal, etc...)
  39352. * @returns true if data is present
  39353. */
  39354. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39355. if (!this._vertexBuffers) {
  39356. if (this._delayInfo) {
  39357. return this._delayInfo.indexOf(kind) !== -1;
  39358. }
  39359. return false;
  39360. }
  39361. return this._vertexBuffers[kind] !== undefined;
  39362. };
  39363. /**
  39364. * Gets a list of all attached data kinds (Position, normal, etc...)
  39365. * @returns a list of string containing all kinds
  39366. */
  39367. Geometry.prototype.getVerticesDataKinds = function () {
  39368. var result = [];
  39369. var kind;
  39370. if (!this._vertexBuffers && this._delayInfo) {
  39371. for (kind in this._delayInfo) {
  39372. result.push(kind);
  39373. }
  39374. }
  39375. else {
  39376. for (kind in this._vertexBuffers) {
  39377. result.push(kind);
  39378. }
  39379. }
  39380. return result;
  39381. };
  39382. /**
  39383. * Update index buffer
  39384. * @param indices defines the indices to store in the index buffer
  39385. * @param offset defines the offset in the target buffer where to store the data
  39386. */
  39387. Geometry.prototype.updateIndices = function (indices, offset) {
  39388. if (!this._indexBuffer) {
  39389. return;
  39390. }
  39391. if (!this._indexBufferIsUpdatable) {
  39392. this.setIndices(indices, null, true);
  39393. }
  39394. else {
  39395. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39396. }
  39397. };
  39398. /**
  39399. * Creates a new index buffer
  39400. * @param indices defines the indices to store in the index buffer
  39401. * @param totalVertices defines the total number of vertices (could be null)
  39402. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39403. */
  39404. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39405. if (totalVertices === void 0) { totalVertices = null; }
  39406. if (updatable === void 0) { updatable = false; }
  39407. if (this._indexBuffer) {
  39408. this._engine._releaseBuffer(this._indexBuffer);
  39409. }
  39410. this._disposeVertexArrayObjects();
  39411. this._indices = indices;
  39412. this._indexBufferIsUpdatable = updatable;
  39413. if (this._meshes.length !== 0 && this._indices) {
  39414. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39415. }
  39416. if (totalVertices != undefined) { // including null and undefined
  39417. this._totalVertices = totalVertices;
  39418. }
  39419. var meshes = this._meshes;
  39420. var numOfMeshes = meshes.length;
  39421. for (var index = 0; index < numOfMeshes; index++) {
  39422. meshes[index]._createGlobalSubMesh(true);
  39423. }
  39424. this.notifyUpdate();
  39425. };
  39426. /**
  39427. * Return the total number of indices
  39428. * @returns the total number of indices
  39429. */
  39430. Geometry.prototype.getTotalIndices = function () {
  39431. if (!this.isReady()) {
  39432. return 0;
  39433. }
  39434. return this._indices.length;
  39435. };
  39436. /**
  39437. * Gets the index buffer array
  39438. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39439. * @returns the index buffer array
  39440. */
  39441. Geometry.prototype.getIndices = function (copyWhenShared) {
  39442. if (!this.isReady()) {
  39443. return null;
  39444. }
  39445. var orig = this._indices;
  39446. if (!copyWhenShared || this._meshes.length === 1) {
  39447. return orig;
  39448. }
  39449. else {
  39450. var len = orig.length;
  39451. var copy = [];
  39452. for (var i = 0; i < len; i++) {
  39453. copy.push(orig[i]);
  39454. }
  39455. return copy;
  39456. }
  39457. };
  39458. /**
  39459. * Gets the index buffer
  39460. * @return the index buffer
  39461. */
  39462. Geometry.prototype.getIndexBuffer = function () {
  39463. if (!this.isReady()) {
  39464. return null;
  39465. }
  39466. return this._indexBuffer;
  39467. };
  39468. /** @hidden */
  39469. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39470. if (effect === void 0) { effect = null; }
  39471. if (!effect || !this._vertexArrayObjects) {
  39472. return;
  39473. }
  39474. if (this._vertexArrayObjects[effect.key]) {
  39475. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39476. delete this._vertexArrayObjects[effect.key];
  39477. }
  39478. };
  39479. /**
  39480. * Release the associated resources for a specific mesh
  39481. * @param mesh defines the source mesh
  39482. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39483. */
  39484. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39485. var meshes = this._meshes;
  39486. var index = meshes.indexOf(mesh);
  39487. if (index === -1) {
  39488. return;
  39489. }
  39490. meshes.splice(index, 1);
  39491. mesh._geometry = null;
  39492. if (meshes.length === 0 && shouldDispose) {
  39493. this.dispose();
  39494. }
  39495. };
  39496. /**
  39497. * Apply current geometry to a given mesh
  39498. * @param mesh defines the mesh to apply geometry to
  39499. */
  39500. Geometry.prototype.applyToMesh = function (mesh) {
  39501. if (mesh._geometry === this) {
  39502. return;
  39503. }
  39504. var previousGeometry = mesh._geometry;
  39505. if (previousGeometry) {
  39506. previousGeometry.releaseForMesh(mesh);
  39507. }
  39508. var meshes = this._meshes;
  39509. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39510. mesh._geometry = this;
  39511. this._scene.pushGeometry(this);
  39512. meshes.push(mesh);
  39513. if (this.isReady()) {
  39514. this._applyToMesh(mesh);
  39515. }
  39516. else {
  39517. mesh._boundingInfo = this._boundingInfo;
  39518. }
  39519. };
  39520. Geometry.prototype._updateExtend = function (data) {
  39521. if (data === void 0) { data = null; }
  39522. if (!data) {
  39523. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39524. }
  39525. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39526. };
  39527. Geometry.prototype._applyToMesh = function (mesh) {
  39528. var numOfMeshes = this._meshes.length;
  39529. // vertexBuffers
  39530. for (var kind in this._vertexBuffers) {
  39531. if (numOfMeshes === 1) {
  39532. this._vertexBuffers[kind].create();
  39533. }
  39534. var buffer = this._vertexBuffers[kind].getBuffer();
  39535. if (buffer)
  39536. buffer.references = numOfMeshes;
  39537. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39538. if (!this._extend) {
  39539. this._updateExtend();
  39540. }
  39541. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39542. mesh._createGlobalSubMesh(false);
  39543. //bounding info was just created again, world matrix should be applied again.
  39544. mesh._updateBoundingInfo();
  39545. }
  39546. }
  39547. // indexBuffer
  39548. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39549. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39550. }
  39551. if (this._indexBuffer) {
  39552. this._indexBuffer.references = numOfMeshes;
  39553. }
  39554. };
  39555. Geometry.prototype.notifyUpdate = function (kind) {
  39556. if (this.onGeometryUpdated) {
  39557. this.onGeometryUpdated(this, kind);
  39558. }
  39559. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39560. var mesh = _a[_i];
  39561. mesh._markSubMeshesAsAttributesDirty();
  39562. }
  39563. };
  39564. /**
  39565. * Load the geometry if it was flagged as delay loaded
  39566. * @param scene defines the hosting scene
  39567. * @param onLoaded defines a callback called when the geometry is loaded
  39568. */
  39569. Geometry.prototype.load = function (scene, onLoaded) {
  39570. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39571. return;
  39572. }
  39573. if (this.isReady()) {
  39574. if (onLoaded) {
  39575. onLoaded();
  39576. }
  39577. return;
  39578. }
  39579. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39580. this._queueLoad(scene, onLoaded);
  39581. };
  39582. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39583. var _this = this;
  39584. if (!this.delayLoadingFile) {
  39585. return;
  39586. }
  39587. scene._addPendingData(this);
  39588. scene._loadFile(this.delayLoadingFile, function (data) {
  39589. if (!_this._delayLoadingFunction) {
  39590. return;
  39591. }
  39592. _this._delayLoadingFunction(JSON.parse(data), _this);
  39593. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39594. _this._delayInfo = [];
  39595. scene._removePendingData(_this);
  39596. var meshes = _this._meshes;
  39597. var numOfMeshes = meshes.length;
  39598. for (var index = 0; index < numOfMeshes; index++) {
  39599. _this._applyToMesh(meshes[index]);
  39600. }
  39601. if (onLoaded) {
  39602. onLoaded();
  39603. }
  39604. }, undefined, true);
  39605. };
  39606. /**
  39607. * Invert the geometry to move from a right handed system to a left handed one.
  39608. */
  39609. Geometry.prototype.toLeftHanded = function () {
  39610. // Flip faces
  39611. var tIndices = this.getIndices(false);
  39612. if (tIndices != null && tIndices.length > 0) {
  39613. for (var i = 0; i < tIndices.length; i += 3) {
  39614. var tTemp = tIndices[i + 0];
  39615. tIndices[i + 0] = tIndices[i + 2];
  39616. tIndices[i + 2] = tTemp;
  39617. }
  39618. this.setIndices(tIndices);
  39619. }
  39620. // Negate position.z
  39621. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39622. if (tPositions != null && tPositions.length > 0) {
  39623. for (var i = 0; i < tPositions.length; i += 3) {
  39624. tPositions[i + 2] = -tPositions[i + 2];
  39625. }
  39626. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39627. }
  39628. // Negate normal.z
  39629. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39630. if (tNormals != null && tNormals.length > 0) {
  39631. for (var i = 0; i < tNormals.length; i += 3) {
  39632. tNormals[i + 2] = -tNormals[i + 2];
  39633. }
  39634. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39635. }
  39636. };
  39637. // Cache
  39638. /** @hidden */
  39639. Geometry.prototype._resetPointsArrayCache = function () {
  39640. this._positions = null;
  39641. };
  39642. /** @hidden */
  39643. Geometry.prototype._generatePointsArray = function () {
  39644. if (this._positions)
  39645. return true;
  39646. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39647. if (!data || data.length === 0) {
  39648. return false;
  39649. }
  39650. this._positions = [];
  39651. for (var index = 0; index < data.length; index += 3) {
  39652. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39653. }
  39654. return true;
  39655. };
  39656. /**
  39657. * Gets a value indicating if the geometry is disposed
  39658. * @returns true if the geometry was disposed
  39659. */
  39660. Geometry.prototype.isDisposed = function () {
  39661. return this._isDisposed;
  39662. };
  39663. Geometry.prototype._disposeVertexArrayObjects = function () {
  39664. if (this._vertexArrayObjects) {
  39665. for (var kind in this._vertexArrayObjects) {
  39666. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39667. }
  39668. this._vertexArrayObjects = {};
  39669. }
  39670. };
  39671. /**
  39672. * Free all associated resources
  39673. */
  39674. Geometry.prototype.dispose = function () {
  39675. var meshes = this._meshes;
  39676. var numOfMeshes = meshes.length;
  39677. var index;
  39678. for (index = 0; index < numOfMeshes; index++) {
  39679. this.releaseForMesh(meshes[index]);
  39680. }
  39681. this._meshes = [];
  39682. this._disposeVertexArrayObjects();
  39683. for (var kind in this._vertexBuffers) {
  39684. this._vertexBuffers[kind].dispose();
  39685. }
  39686. this._vertexBuffers = {};
  39687. this._totalVertices = 0;
  39688. if (this._indexBuffer) {
  39689. this._engine._releaseBuffer(this._indexBuffer);
  39690. }
  39691. this._indexBuffer = null;
  39692. this._indices = [];
  39693. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39694. this.delayLoadingFile = null;
  39695. this._delayLoadingFunction = null;
  39696. this._delayInfo = [];
  39697. this._boundingInfo = null;
  39698. this._scene.removeGeometry(this);
  39699. this._isDisposed = true;
  39700. };
  39701. /**
  39702. * Clone the current geometry into a new geometry
  39703. * @param id defines the unique ID of the new geometry
  39704. * @returns a new geometry object
  39705. */
  39706. Geometry.prototype.copy = function (id) {
  39707. var vertexData = new BABYLON.VertexData();
  39708. vertexData.indices = [];
  39709. var indices = this.getIndices();
  39710. if (indices) {
  39711. for (var index = 0; index < indices.length; index++) {
  39712. vertexData.indices.push(indices[index]);
  39713. }
  39714. }
  39715. var updatable = false;
  39716. var stopChecking = false;
  39717. var kind;
  39718. for (kind in this._vertexBuffers) {
  39719. // using slice() to make a copy of the array and not just reference it
  39720. var data = this.getVerticesData(kind);
  39721. if (data instanceof Float32Array) {
  39722. vertexData.set(new Float32Array(data), kind);
  39723. }
  39724. else {
  39725. vertexData.set(data.slice(0), kind);
  39726. }
  39727. if (!stopChecking) {
  39728. var vb = this.getVertexBuffer(kind);
  39729. if (vb) {
  39730. updatable = vb.isUpdatable();
  39731. stopChecking = !updatable;
  39732. }
  39733. }
  39734. }
  39735. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39736. geometry.delayLoadState = this.delayLoadState;
  39737. geometry.delayLoadingFile = this.delayLoadingFile;
  39738. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39739. for (kind in this._delayInfo) {
  39740. geometry._delayInfo = geometry._delayInfo || [];
  39741. geometry._delayInfo.push(kind);
  39742. }
  39743. // Bounding info
  39744. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39745. return geometry;
  39746. };
  39747. /**
  39748. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39749. * @return a JSON representation of the current geometry data (without the vertices data)
  39750. */
  39751. Geometry.prototype.serialize = function () {
  39752. var serializationObject = {};
  39753. serializationObject.id = this.id;
  39754. serializationObject.updatable = this._updatable;
  39755. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39756. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39757. }
  39758. return serializationObject;
  39759. };
  39760. Geometry.prototype.toNumberArray = function (origin) {
  39761. if (Array.isArray(origin)) {
  39762. return origin;
  39763. }
  39764. else {
  39765. return Array.prototype.slice.call(origin);
  39766. }
  39767. };
  39768. /**
  39769. * Serialize all vertices data into a JSON oject
  39770. * @returns a JSON representation of the current geometry data
  39771. */
  39772. Geometry.prototype.serializeVerticeData = function () {
  39773. var serializationObject = this.serialize();
  39774. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39775. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39776. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39777. serializationObject.positions._updatable = true;
  39778. }
  39779. }
  39780. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39781. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39782. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39783. serializationObject.normals._updatable = true;
  39784. }
  39785. }
  39786. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39787. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39788. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39789. serializationObject.tangets._updatable = true;
  39790. }
  39791. }
  39792. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39793. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39794. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39795. serializationObject.uvs._updatable = true;
  39796. }
  39797. }
  39798. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39799. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39800. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39801. serializationObject.uv2s._updatable = true;
  39802. }
  39803. }
  39804. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39805. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39806. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39807. serializationObject.uv3s._updatable = true;
  39808. }
  39809. }
  39810. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39811. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39812. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39813. serializationObject.uv4s._updatable = true;
  39814. }
  39815. }
  39816. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39817. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39818. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39819. serializationObject.uv5s._updatable = true;
  39820. }
  39821. }
  39822. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39823. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39824. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39825. serializationObject.uv6s._updatable = true;
  39826. }
  39827. }
  39828. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39829. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39830. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39831. serializationObject.colors._updatable = true;
  39832. }
  39833. }
  39834. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39835. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39836. serializationObject.matricesIndices._isExpanded = true;
  39837. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39838. serializationObject.matricesIndices._updatable = true;
  39839. }
  39840. }
  39841. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39842. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39843. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39844. serializationObject.matricesWeights._updatable = true;
  39845. }
  39846. }
  39847. serializationObject.indices = this.toNumberArray(this.getIndices());
  39848. return serializationObject;
  39849. };
  39850. // Statics
  39851. /**
  39852. * Extracts a clone of a mesh geometry
  39853. * @param mesh defines the source mesh
  39854. * @param id defines the unique ID of the new geometry object
  39855. * @returns the new geometry object
  39856. */
  39857. Geometry.ExtractFromMesh = function (mesh, id) {
  39858. var geometry = mesh._geometry;
  39859. if (!geometry) {
  39860. return null;
  39861. }
  39862. return geometry.copy(id);
  39863. };
  39864. /**
  39865. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39866. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39867. * Be aware Math.random() could cause collisions, but:
  39868. * "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"
  39869. * @returns a string containing a new GUID
  39870. */
  39871. Geometry.RandomId = function () {
  39872. return BABYLON.Tools.RandomId();
  39873. };
  39874. /** @hidden */
  39875. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39876. var scene = mesh.getScene();
  39877. // Geometry
  39878. var geometryId = parsedGeometry.geometryId;
  39879. if (geometryId) {
  39880. var geometry = scene.getGeometryByID(geometryId);
  39881. if (geometry) {
  39882. geometry.applyToMesh(mesh);
  39883. }
  39884. }
  39885. else if (parsedGeometry instanceof ArrayBuffer) {
  39886. var binaryInfo = mesh._binaryInfo;
  39887. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39888. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39889. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39890. }
  39891. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39892. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39893. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39894. }
  39895. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39896. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39897. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39898. }
  39899. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39900. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39901. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39902. }
  39903. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39904. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39905. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39906. }
  39907. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39908. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39909. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39910. }
  39911. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39912. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39913. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39914. }
  39915. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39916. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39917. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39918. }
  39919. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39920. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39921. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39922. }
  39923. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39924. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39925. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39926. }
  39927. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39928. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39929. var floatIndices = [];
  39930. for (var i = 0; i < matricesIndicesData.length; i++) {
  39931. var index = matricesIndicesData[i];
  39932. floatIndices.push(index & 0x000000FF);
  39933. floatIndices.push((index & 0x0000FF00) >> 8);
  39934. floatIndices.push((index & 0x00FF0000) >> 16);
  39935. floatIndices.push(index >> 24);
  39936. }
  39937. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  39938. }
  39939. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39940. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39941. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39942. }
  39943. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39944. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39945. mesh.setIndices(indicesData, null);
  39946. }
  39947. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39948. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39949. mesh.subMeshes = [];
  39950. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39951. var materialIndex = subMeshesData[(i * 5) + 0];
  39952. var verticesStart = subMeshesData[(i * 5) + 1];
  39953. var verticesCount = subMeshesData[(i * 5) + 2];
  39954. var indexStart = subMeshesData[(i * 5) + 3];
  39955. var indexCount = subMeshesData[(i * 5) + 4];
  39956. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39957. }
  39958. }
  39959. }
  39960. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39961. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39962. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39963. if (parsedGeometry.tangents) {
  39964. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39965. }
  39966. if (parsedGeometry.uvs) {
  39967. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39968. }
  39969. if (parsedGeometry.uvs2) {
  39970. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39971. }
  39972. if (parsedGeometry.uvs3) {
  39973. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39974. }
  39975. if (parsedGeometry.uvs4) {
  39976. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39977. }
  39978. if (parsedGeometry.uvs5) {
  39979. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39980. }
  39981. if (parsedGeometry.uvs6) {
  39982. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39983. }
  39984. if (parsedGeometry.colors) {
  39985. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39986. }
  39987. if (parsedGeometry.matricesIndices) {
  39988. if (!parsedGeometry.matricesIndices._isExpanded) {
  39989. var floatIndices = [];
  39990. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39991. var matricesIndex = parsedGeometry.matricesIndices[i];
  39992. floatIndices.push(matricesIndex & 0x000000FF);
  39993. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39994. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39995. floatIndices.push(matricesIndex >> 24);
  39996. }
  39997. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39998. }
  39999. else {
  40000. delete parsedGeometry.matricesIndices._isExpanded;
  40001. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40002. }
  40003. }
  40004. if (parsedGeometry.matricesIndicesExtra) {
  40005. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40006. var floatIndices = [];
  40007. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40008. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40009. floatIndices.push(matricesIndex & 0x000000FF);
  40010. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40011. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40012. floatIndices.push(matricesIndex >> 24);
  40013. }
  40014. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40015. }
  40016. else {
  40017. delete parsedGeometry.matricesIndices._isExpanded;
  40018. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40019. }
  40020. }
  40021. if (parsedGeometry.matricesWeights) {
  40022. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40023. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40024. }
  40025. if (parsedGeometry.matricesWeightsExtra) {
  40026. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40027. }
  40028. mesh.setIndices(parsedGeometry.indices, null);
  40029. }
  40030. // SubMeshes
  40031. if (parsedGeometry.subMeshes) {
  40032. mesh.subMeshes = [];
  40033. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40034. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40035. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40036. }
  40037. }
  40038. // Flat shading
  40039. if (mesh._shouldGenerateFlatShading) {
  40040. mesh.convertToFlatShadedMesh();
  40041. delete mesh._shouldGenerateFlatShading;
  40042. }
  40043. // Update
  40044. mesh.computeWorldMatrix(true);
  40045. // Octree
  40046. var sceneOctree = scene.selectionOctree;
  40047. if (sceneOctree !== undefined && sceneOctree !== null) {
  40048. sceneOctree.addMesh(mesh);
  40049. }
  40050. };
  40051. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40052. var epsilon = 1e-3;
  40053. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40054. return;
  40055. }
  40056. var noInfluenceBoneIndex = 0.0;
  40057. if (parsedGeometry.skeletonId > -1) {
  40058. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40059. if (!skeleton) {
  40060. return;
  40061. }
  40062. noInfluenceBoneIndex = skeleton.bones.length;
  40063. }
  40064. else {
  40065. return;
  40066. }
  40067. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40068. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40069. var matricesWeights = parsedGeometry.matricesWeights;
  40070. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40071. var influencers = parsedGeometry.numBoneInfluencer;
  40072. var size = matricesWeights.length;
  40073. for (var i = 0; i < size; i += 4) {
  40074. var weight = 0.0;
  40075. var firstZeroWeight = -1;
  40076. for (var j = 0; j < 4; j++) {
  40077. var w = matricesWeights[i + j];
  40078. weight += w;
  40079. if (w < epsilon && firstZeroWeight < 0) {
  40080. firstZeroWeight = j;
  40081. }
  40082. }
  40083. if (matricesWeightsExtra) {
  40084. for (var j = 0; j < 4; j++) {
  40085. var w = matricesWeightsExtra[i + j];
  40086. weight += w;
  40087. if (w < epsilon && firstZeroWeight < 0) {
  40088. firstZeroWeight = j + 4;
  40089. }
  40090. }
  40091. }
  40092. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40093. firstZeroWeight = influencers - 1;
  40094. }
  40095. if (weight > epsilon) {
  40096. var mweight = 1.0 / weight;
  40097. for (var j = 0; j < 4; j++) {
  40098. matricesWeights[i + j] *= mweight;
  40099. }
  40100. if (matricesWeightsExtra) {
  40101. for (var j = 0; j < 4; j++) {
  40102. matricesWeightsExtra[i + j] *= mweight;
  40103. }
  40104. }
  40105. }
  40106. else {
  40107. if (firstZeroWeight >= 4) {
  40108. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40109. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40110. }
  40111. else {
  40112. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40113. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40114. }
  40115. }
  40116. }
  40117. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40118. if (parsedGeometry.matricesWeightsExtra) {
  40119. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40120. }
  40121. };
  40122. /**
  40123. * Create a new geometry from persisted data (Using .babylon file format)
  40124. * @param parsedVertexData defines the persisted data
  40125. * @param scene defines the hosting scene
  40126. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40127. * @returns the new geometry object
  40128. */
  40129. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40130. if (scene.getGeometryByID(parsedVertexData.id)) {
  40131. return null; // null since geometry could be something else than a box...
  40132. }
  40133. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40134. if (BABYLON.Tags) {
  40135. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40136. }
  40137. if (parsedVertexData.delayLoadingFile) {
  40138. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40139. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40140. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40141. geometry._delayInfo = [];
  40142. if (parsedVertexData.hasUVs) {
  40143. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40144. }
  40145. if (parsedVertexData.hasUVs2) {
  40146. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40147. }
  40148. if (parsedVertexData.hasUVs3) {
  40149. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40150. }
  40151. if (parsedVertexData.hasUVs4) {
  40152. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40153. }
  40154. if (parsedVertexData.hasUVs5) {
  40155. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40156. }
  40157. if (parsedVertexData.hasUVs6) {
  40158. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40159. }
  40160. if (parsedVertexData.hasColors) {
  40161. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40162. }
  40163. if (parsedVertexData.hasMatricesIndices) {
  40164. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40165. }
  40166. if (parsedVertexData.hasMatricesWeights) {
  40167. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40168. }
  40169. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40170. }
  40171. else {
  40172. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40173. }
  40174. scene.pushGeometry(geometry, true);
  40175. return geometry;
  40176. };
  40177. return Geometry;
  40178. }());
  40179. BABYLON.Geometry = Geometry;
  40180. // Primitives
  40181. /// Abstract class
  40182. /**
  40183. * Abstract class used to provide common services for all typed geometries
  40184. * @hidden
  40185. */
  40186. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40187. __extends(_PrimitiveGeometry, _super);
  40188. /**
  40189. * Creates a new typed geometry
  40190. * @param id defines the unique ID of the geometry
  40191. * @param scene defines the hosting scene
  40192. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40193. * @param mesh defines the hosting mesh (can be null)
  40194. */
  40195. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40196. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40197. if (mesh === void 0) { mesh = null; }
  40198. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40199. _this._canBeRegenerated = _canBeRegenerated;
  40200. _this._beingRegenerated = true;
  40201. _this.regenerate();
  40202. _this._beingRegenerated = false;
  40203. return _this;
  40204. }
  40205. /**
  40206. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40207. * @returns true if the geometry can be regenerated
  40208. */
  40209. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40210. return this._canBeRegenerated;
  40211. };
  40212. /**
  40213. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40214. */
  40215. _PrimitiveGeometry.prototype.regenerate = function () {
  40216. if (!this._canBeRegenerated) {
  40217. return;
  40218. }
  40219. this._beingRegenerated = true;
  40220. this.setAllVerticesData(this._regenerateVertexData(), false);
  40221. this._beingRegenerated = false;
  40222. };
  40223. /**
  40224. * Clone the geometry
  40225. * @param id defines the unique ID of the new geometry
  40226. * @returns the new geometry
  40227. */
  40228. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40229. return _super.prototype.copy.call(this, id);
  40230. };
  40231. // overrides
  40232. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40233. if (!this._beingRegenerated) {
  40234. return;
  40235. }
  40236. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40237. };
  40238. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40239. if (!this._beingRegenerated) {
  40240. return;
  40241. }
  40242. _super.prototype.setVerticesData.call(this, kind, data, false);
  40243. };
  40244. // to override
  40245. /** @hidden */
  40246. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40247. throw new Error("Abstract method");
  40248. };
  40249. _PrimitiveGeometry.prototype.copy = function (id) {
  40250. throw new Error("Must be overriden in sub-classes.");
  40251. };
  40252. _PrimitiveGeometry.prototype.serialize = function () {
  40253. var serializationObject = _super.prototype.serialize.call(this);
  40254. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40255. return serializationObject;
  40256. };
  40257. return _PrimitiveGeometry;
  40258. }(Geometry));
  40259. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40260. /**
  40261. * Creates a ribbon geometry
  40262. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40263. */
  40264. var RibbonGeometry = /** @class */ (function (_super) {
  40265. __extends(RibbonGeometry, _super);
  40266. /**
  40267. * Creates a ribbon geometry
  40268. * @param id defines the unique ID of the geometry
  40269. * @param scene defines the hosting scene
  40270. * @param pathArray defines the array of paths to use
  40271. * @param closeArray defines if the last path and the first path must be joined
  40272. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40273. * @param offset defines the offset between points
  40274. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40275. * @param mesh defines the hosting mesh (can be null)
  40276. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40277. */
  40278. function RibbonGeometry(id, scene,
  40279. /**
  40280. * Defines the array of paths to use
  40281. */
  40282. pathArray,
  40283. /**
  40284. * Defines if the last and first points of each path in your pathArray must be joined
  40285. */
  40286. closeArray,
  40287. /**
  40288. * Defines if the last and first points of each path in your pathArray must be joined
  40289. */
  40290. closePath,
  40291. /**
  40292. * Defines the offset between points
  40293. */
  40294. offset, canBeRegenerated, mesh,
  40295. /**
  40296. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40297. */
  40298. side) {
  40299. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40300. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40301. _this.pathArray = pathArray;
  40302. _this.closeArray = closeArray;
  40303. _this.closePath = closePath;
  40304. _this.offset = offset;
  40305. _this.side = side;
  40306. return _this;
  40307. }
  40308. /** @hidden */
  40309. RibbonGeometry.prototype._regenerateVertexData = function () {
  40310. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40311. };
  40312. RibbonGeometry.prototype.copy = function (id) {
  40313. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40314. };
  40315. return RibbonGeometry;
  40316. }(_PrimitiveGeometry));
  40317. BABYLON.RibbonGeometry = RibbonGeometry;
  40318. /**
  40319. * Creates a box geometry
  40320. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40321. */
  40322. var BoxGeometry = /** @class */ (function (_super) {
  40323. __extends(BoxGeometry, _super);
  40324. /**
  40325. * Creates a box geometry
  40326. * @param id defines the unique ID of the geometry
  40327. * @param scene defines the hosting scene
  40328. * @param size defines the zise of the box (width, height and depth are the same)
  40329. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40330. * @param mesh defines the hosting mesh (can be null)
  40331. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40332. */
  40333. function BoxGeometry(id, scene,
  40334. /**
  40335. * Defines the zise of the box (width, height and depth are the same)
  40336. */
  40337. size, canBeRegenerated, mesh,
  40338. /**
  40339. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40340. */
  40341. side) {
  40342. if (mesh === void 0) { mesh = null; }
  40343. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40344. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40345. _this.size = size;
  40346. _this.side = side;
  40347. return _this;
  40348. }
  40349. BoxGeometry.prototype._regenerateVertexData = function () {
  40350. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40351. };
  40352. BoxGeometry.prototype.copy = function (id) {
  40353. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40354. };
  40355. BoxGeometry.prototype.serialize = function () {
  40356. var serializationObject = _super.prototype.serialize.call(this);
  40357. serializationObject.size = this.size;
  40358. return serializationObject;
  40359. };
  40360. BoxGeometry.Parse = function (parsedBox, scene) {
  40361. if (scene.getGeometryByID(parsedBox.id)) {
  40362. return null; // null since geometry could be something else than a box...
  40363. }
  40364. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40365. if (BABYLON.Tags) {
  40366. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40367. }
  40368. scene.pushGeometry(box, true);
  40369. return box;
  40370. };
  40371. return BoxGeometry;
  40372. }(_PrimitiveGeometry));
  40373. BABYLON.BoxGeometry = BoxGeometry;
  40374. /**
  40375. * Creates a sphere geometry
  40376. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40377. */
  40378. var SphereGeometry = /** @class */ (function (_super) {
  40379. __extends(SphereGeometry, _super);
  40380. /**
  40381. * Create a new sphere geometry
  40382. * @param id defines the unique ID of the geometry
  40383. * @param scene defines the hosting scene
  40384. * @param segments defines the number of segments to use to create the sphere
  40385. * @param diameter defines the diameter of the sphere
  40386. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40387. * @param mesh defines the hosting mesh (can be null)
  40388. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40389. */
  40390. function SphereGeometry(id, scene,
  40391. /**
  40392. * Defines the number of segments to use to create the sphere
  40393. */
  40394. segments,
  40395. /**
  40396. * Defines the diameter of the sphere
  40397. */
  40398. diameter, canBeRegenerated, mesh,
  40399. /**
  40400. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40401. */
  40402. side) {
  40403. if (mesh === void 0) { mesh = null; }
  40404. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40405. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40406. _this.segments = segments;
  40407. _this.diameter = diameter;
  40408. _this.side = side;
  40409. return _this;
  40410. }
  40411. SphereGeometry.prototype._regenerateVertexData = function () {
  40412. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40413. };
  40414. SphereGeometry.prototype.copy = function (id) {
  40415. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40416. };
  40417. SphereGeometry.prototype.serialize = function () {
  40418. var serializationObject = _super.prototype.serialize.call(this);
  40419. serializationObject.segments = this.segments;
  40420. serializationObject.diameter = this.diameter;
  40421. return serializationObject;
  40422. };
  40423. SphereGeometry.Parse = function (parsedSphere, scene) {
  40424. if (scene.getGeometryByID(parsedSphere.id)) {
  40425. return null; // null since geometry could be something else than a sphere...
  40426. }
  40427. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40428. if (BABYLON.Tags) {
  40429. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40430. }
  40431. scene.pushGeometry(sphere, true);
  40432. return sphere;
  40433. };
  40434. return SphereGeometry;
  40435. }(_PrimitiveGeometry));
  40436. BABYLON.SphereGeometry = SphereGeometry;
  40437. /**
  40438. * Creates a disc geometry
  40439. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40440. */
  40441. var DiscGeometry = /** @class */ (function (_super) {
  40442. __extends(DiscGeometry, _super);
  40443. /**
  40444. * Creates a new disc geometry
  40445. * @param id defines the unique ID of the geometry
  40446. * @param scene defines the hosting scene
  40447. * @param radius defines the radius of the disc
  40448. * @param tessellation defines the tesselation factor to apply to the disc
  40449. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40450. * @param mesh defines the hosting mesh (can be null)
  40451. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40452. */
  40453. function DiscGeometry(id, scene,
  40454. /**
  40455. * Defines the radius of the disc
  40456. */
  40457. radius,
  40458. /**
  40459. * Defines the tesselation factor to apply to the disc
  40460. */
  40461. tessellation, canBeRegenerated, mesh,
  40462. /**
  40463. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40464. */
  40465. side) {
  40466. if (mesh === void 0) { mesh = null; }
  40467. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40468. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40469. _this.radius = radius;
  40470. _this.tessellation = tessellation;
  40471. _this.side = side;
  40472. return _this;
  40473. }
  40474. DiscGeometry.prototype._regenerateVertexData = function () {
  40475. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40476. };
  40477. DiscGeometry.prototype.copy = function (id) {
  40478. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40479. };
  40480. return DiscGeometry;
  40481. }(_PrimitiveGeometry));
  40482. BABYLON.DiscGeometry = DiscGeometry;
  40483. /**
  40484. * Creates a new cylinder geometry
  40485. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40486. */
  40487. var CylinderGeometry = /** @class */ (function (_super) {
  40488. __extends(CylinderGeometry, _super);
  40489. /**
  40490. * Creates a new cylinder geometry
  40491. * @param id defines the unique ID of the geometry
  40492. * @param scene defines the hosting scene
  40493. * @param height defines the height of the cylinder
  40494. * @param diameterTop defines the diameter of the cylinder's top cap
  40495. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40496. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40497. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40498. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40499. * @param mesh defines the hosting mesh (can be null)
  40500. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40501. */
  40502. function CylinderGeometry(id, scene,
  40503. /**
  40504. * Defines the height of the cylinder
  40505. */
  40506. height,
  40507. /**
  40508. * Defines the diameter of the cylinder's top cap
  40509. */
  40510. diameterTop,
  40511. /**
  40512. * Defines the diameter of the cylinder's bottom cap
  40513. */
  40514. diameterBottom,
  40515. /**
  40516. * Defines the tessellation factor to apply to the cylinder
  40517. */
  40518. tessellation,
  40519. /**
  40520. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40521. */
  40522. subdivisions, canBeRegenerated, mesh,
  40523. /**
  40524. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40525. */
  40526. side) {
  40527. if (subdivisions === void 0) { subdivisions = 1; }
  40528. if (mesh === void 0) { mesh = null; }
  40529. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40530. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40531. _this.height = height;
  40532. _this.diameterTop = diameterTop;
  40533. _this.diameterBottom = diameterBottom;
  40534. _this.tessellation = tessellation;
  40535. _this.subdivisions = subdivisions;
  40536. _this.side = side;
  40537. return _this;
  40538. }
  40539. CylinderGeometry.prototype._regenerateVertexData = function () {
  40540. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40541. };
  40542. CylinderGeometry.prototype.copy = function (id) {
  40543. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40544. };
  40545. CylinderGeometry.prototype.serialize = function () {
  40546. var serializationObject = _super.prototype.serialize.call(this);
  40547. serializationObject.height = this.height;
  40548. serializationObject.diameterTop = this.diameterTop;
  40549. serializationObject.diameterBottom = this.diameterBottom;
  40550. serializationObject.tessellation = this.tessellation;
  40551. return serializationObject;
  40552. };
  40553. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40554. if (scene.getGeometryByID(parsedCylinder.id)) {
  40555. return null; // null since geometry could be something else than a cylinder...
  40556. }
  40557. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40558. if (BABYLON.Tags) {
  40559. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40560. }
  40561. scene.pushGeometry(cylinder, true);
  40562. return cylinder;
  40563. };
  40564. return CylinderGeometry;
  40565. }(_PrimitiveGeometry));
  40566. BABYLON.CylinderGeometry = CylinderGeometry;
  40567. /**
  40568. * Creates a new torus geometry
  40569. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40570. */
  40571. var TorusGeometry = /** @class */ (function (_super) {
  40572. __extends(TorusGeometry, _super);
  40573. /**
  40574. * Creates a new torus geometry
  40575. * @param id defines the unique ID of the geometry
  40576. * @param scene defines the hosting scene
  40577. * @param diameter defines the diameter of the torus
  40578. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40579. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40580. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40581. * @param mesh defines the hosting mesh (can be null)
  40582. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40583. */
  40584. function TorusGeometry(id, scene,
  40585. /**
  40586. * Defines the diameter of the torus
  40587. */
  40588. diameter,
  40589. /**
  40590. * Defines the thickness of the torus (ie. internal diameter)
  40591. */
  40592. thickness,
  40593. /**
  40594. * Defines the tesselation factor to apply to the torus
  40595. */
  40596. tessellation, canBeRegenerated, mesh,
  40597. /**
  40598. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40599. */
  40600. side) {
  40601. if (mesh === void 0) { mesh = null; }
  40602. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40603. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40604. _this.diameter = diameter;
  40605. _this.thickness = thickness;
  40606. _this.tessellation = tessellation;
  40607. _this.side = side;
  40608. return _this;
  40609. }
  40610. TorusGeometry.prototype._regenerateVertexData = function () {
  40611. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40612. };
  40613. TorusGeometry.prototype.copy = function (id) {
  40614. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40615. };
  40616. TorusGeometry.prototype.serialize = function () {
  40617. var serializationObject = _super.prototype.serialize.call(this);
  40618. serializationObject.diameter = this.diameter;
  40619. serializationObject.thickness = this.thickness;
  40620. serializationObject.tessellation = this.tessellation;
  40621. return serializationObject;
  40622. };
  40623. TorusGeometry.Parse = function (parsedTorus, scene) {
  40624. if (scene.getGeometryByID(parsedTorus.id)) {
  40625. return null; // null since geometry could be something else than a torus...
  40626. }
  40627. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40628. if (BABYLON.Tags) {
  40629. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40630. }
  40631. scene.pushGeometry(torus, true);
  40632. return torus;
  40633. };
  40634. return TorusGeometry;
  40635. }(_PrimitiveGeometry));
  40636. BABYLON.TorusGeometry = TorusGeometry;
  40637. /**
  40638. * Creates a new ground geometry
  40639. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40640. */
  40641. var GroundGeometry = /** @class */ (function (_super) {
  40642. __extends(GroundGeometry, _super);
  40643. /**
  40644. * Creates a new ground geometry
  40645. * @param id defines the unique ID of the geometry
  40646. * @param scene defines the hosting scene
  40647. * @param width defines the width of the ground
  40648. * @param height defines the height of the ground
  40649. * @param subdivisions defines the subdivisions to apply to the ground
  40650. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40651. * @param mesh defines the hosting mesh (can be null)
  40652. */
  40653. function GroundGeometry(id, scene,
  40654. /**
  40655. * Defines the width of the ground
  40656. */
  40657. width,
  40658. /**
  40659. * Defines the height of the ground
  40660. */
  40661. height,
  40662. /**
  40663. * Defines the subdivisions to apply to the ground
  40664. */
  40665. subdivisions, canBeRegenerated, mesh) {
  40666. if (mesh === void 0) { mesh = null; }
  40667. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40668. _this.width = width;
  40669. _this.height = height;
  40670. _this.subdivisions = subdivisions;
  40671. return _this;
  40672. }
  40673. GroundGeometry.prototype._regenerateVertexData = function () {
  40674. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40675. };
  40676. GroundGeometry.prototype.copy = function (id) {
  40677. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40678. };
  40679. GroundGeometry.prototype.serialize = function () {
  40680. var serializationObject = _super.prototype.serialize.call(this);
  40681. serializationObject.width = this.width;
  40682. serializationObject.height = this.height;
  40683. serializationObject.subdivisions = this.subdivisions;
  40684. return serializationObject;
  40685. };
  40686. GroundGeometry.Parse = function (parsedGround, scene) {
  40687. if (scene.getGeometryByID(parsedGround.id)) {
  40688. return null; // null since geometry could be something else than a ground...
  40689. }
  40690. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40691. if (BABYLON.Tags) {
  40692. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40693. }
  40694. scene.pushGeometry(ground, true);
  40695. return ground;
  40696. };
  40697. return GroundGeometry;
  40698. }(_PrimitiveGeometry));
  40699. BABYLON.GroundGeometry = GroundGeometry;
  40700. /**
  40701. * Creates a tiled ground geometry
  40702. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40703. */
  40704. var TiledGroundGeometry = /** @class */ (function (_super) {
  40705. __extends(TiledGroundGeometry, _super);
  40706. /**
  40707. * Creates a tiled ground geometry
  40708. * @param id defines the unique ID of the geometry
  40709. * @param scene defines the hosting scene
  40710. * @param xmin defines the minimum value on X axis
  40711. * @param zmin defines the minimum value on Z axis
  40712. * @param xmax defines the maximum value on X axis
  40713. * @param zmax defines the maximum value on Z axis
  40714. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40715. * @param precision defines the precision to use when computing the tiles
  40716. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40717. * @param mesh defines the hosting mesh (can be null)
  40718. */
  40719. function TiledGroundGeometry(id, scene,
  40720. /**
  40721. * Defines the minimum value on X axis
  40722. */
  40723. xmin,
  40724. /**
  40725. * Defines the minimum value on Z axis
  40726. */
  40727. zmin,
  40728. /**
  40729. * Defines the maximum value on X axis
  40730. */
  40731. xmax,
  40732. /**
  40733. * Defines the maximum value on Z axis
  40734. */
  40735. zmax,
  40736. /**
  40737. * Defines the subdivisions to apply to the ground
  40738. */
  40739. subdivisions,
  40740. /**
  40741. * Defines the precision to use when computing the tiles
  40742. */
  40743. precision, canBeRegenerated, mesh) {
  40744. if (mesh === void 0) { mesh = null; }
  40745. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40746. _this.xmin = xmin;
  40747. _this.zmin = zmin;
  40748. _this.xmax = xmax;
  40749. _this.zmax = zmax;
  40750. _this.subdivisions = subdivisions;
  40751. _this.precision = precision;
  40752. return _this;
  40753. }
  40754. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40755. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40756. };
  40757. TiledGroundGeometry.prototype.copy = function (id) {
  40758. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40759. };
  40760. return TiledGroundGeometry;
  40761. }(_PrimitiveGeometry));
  40762. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40763. /**
  40764. * Creates a plane geometry
  40765. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40766. */
  40767. var PlaneGeometry = /** @class */ (function (_super) {
  40768. __extends(PlaneGeometry, _super);
  40769. /**
  40770. * Creates a plane geometry
  40771. * @param id defines the unique ID of the geometry
  40772. * @param scene defines the hosting scene
  40773. * @param size defines the size of the plane (width === height)
  40774. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40775. * @param mesh defines the hosting mesh (can be null)
  40776. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40777. */
  40778. function PlaneGeometry(id, scene,
  40779. /**
  40780. * Defines the size of the plane (width === height)
  40781. */
  40782. size, canBeRegenerated, mesh,
  40783. /**
  40784. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40785. */
  40786. side) {
  40787. if (mesh === void 0) { mesh = null; }
  40788. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40789. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40790. _this.size = size;
  40791. _this.side = side;
  40792. return _this;
  40793. }
  40794. PlaneGeometry.prototype._regenerateVertexData = function () {
  40795. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40796. };
  40797. PlaneGeometry.prototype.copy = function (id) {
  40798. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40799. };
  40800. PlaneGeometry.prototype.serialize = function () {
  40801. var serializationObject = _super.prototype.serialize.call(this);
  40802. serializationObject.size = this.size;
  40803. return serializationObject;
  40804. };
  40805. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40806. if (scene.getGeometryByID(parsedPlane.id)) {
  40807. return null; // null since geometry could be something else than a ground...
  40808. }
  40809. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40810. if (BABYLON.Tags) {
  40811. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40812. }
  40813. scene.pushGeometry(plane, true);
  40814. return plane;
  40815. };
  40816. return PlaneGeometry;
  40817. }(_PrimitiveGeometry));
  40818. BABYLON.PlaneGeometry = PlaneGeometry;
  40819. /**
  40820. * Creates a torus knot geometry
  40821. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40822. */
  40823. var TorusKnotGeometry = /** @class */ (function (_super) {
  40824. __extends(TorusKnotGeometry, _super);
  40825. /**
  40826. * Creates a torus knot geometry
  40827. * @param id defines the unique ID of the geometry
  40828. * @param scene defines the hosting scene
  40829. * @param radius defines the radius of the torus knot
  40830. * @param tube defines the thickness of the torus knot tube
  40831. * @param radialSegments defines the number of radial segments
  40832. * @param tubularSegments defines the number of tubular segments
  40833. * @param p defines the first number of windings
  40834. * @param q defines the second number of windings
  40835. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40836. * @param mesh defines the hosting mesh (can be null)
  40837. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40838. */
  40839. function TorusKnotGeometry(id, scene,
  40840. /**
  40841. * Defines the radius of the torus knot
  40842. */
  40843. radius,
  40844. /**
  40845. * Defines the thickness of the torus knot tube
  40846. */
  40847. tube,
  40848. /**
  40849. * Defines the number of radial segments
  40850. */
  40851. radialSegments,
  40852. /**
  40853. * Defines the number of tubular segments
  40854. */
  40855. tubularSegments,
  40856. /**
  40857. * Defines the first number of windings
  40858. */
  40859. p,
  40860. /**
  40861. * Defines the second number of windings
  40862. */
  40863. q, canBeRegenerated, mesh,
  40864. /**
  40865. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40866. */
  40867. side) {
  40868. if (mesh === void 0) { mesh = null; }
  40869. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40870. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40871. _this.radius = radius;
  40872. _this.tube = tube;
  40873. _this.radialSegments = radialSegments;
  40874. _this.tubularSegments = tubularSegments;
  40875. _this.p = p;
  40876. _this.q = q;
  40877. _this.side = side;
  40878. return _this;
  40879. }
  40880. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40881. 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 });
  40882. };
  40883. TorusKnotGeometry.prototype.copy = function (id) {
  40884. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40885. };
  40886. TorusKnotGeometry.prototype.serialize = function () {
  40887. var serializationObject = _super.prototype.serialize.call(this);
  40888. serializationObject.radius = this.radius;
  40889. serializationObject.tube = this.tube;
  40890. serializationObject.radialSegments = this.radialSegments;
  40891. serializationObject.tubularSegments = this.tubularSegments;
  40892. serializationObject.p = this.p;
  40893. serializationObject.q = this.q;
  40894. return serializationObject;
  40895. };
  40896. ;
  40897. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40898. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40899. return null; // null since geometry could be something else than a ground...
  40900. }
  40901. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40902. if (BABYLON.Tags) {
  40903. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40904. }
  40905. scene.pushGeometry(torusKnot, true);
  40906. return torusKnot;
  40907. };
  40908. return TorusKnotGeometry;
  40909. }(_PrimitiveGeometry));
  40910. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40911. //}
  40912. })(BABYLON || (BABYLON = {}));
  40913. //# sourceMappingURL=babylon.geometry.js.map
  40914. var BABYLON;
  40915. (function (BABYLON) {
  40916. /**
  40917. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40918. */
  40919. var PerformanceMonitor = /** @class */ (function () {
  40920. /**
  40921. * constructor
  40922. * @param frameSampleSize The number of samples required to saturate the sliding window
  40923. */
  40924. function PerformanceMonitor(frameSampleSize) {
  40925. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40926. this._enabled = true;
  40927. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40928. }
  40929. /**
  40930. * Samples current frame
  40931. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40932. */
  40933. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40934. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40935. if (!this._enabled)
  40936. return;
  40937. if (this._lastFrameTimeMs != null) {
  40938. var dt = timeMs - this._lastFrameTimeMs;
  40939. this._rollingFrameTime.add(dt);
  40940. }
  40941. this._lastFrameTimeMs = timeMs;
  40942. };
  40943. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40944. /**
  40945. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40946. * @return Average frame time in milliseconds
  40947. */
  40948. get: function () {
  40949. return this._rollingFrameTime.average;
  40950. },
  40951. enumerable: true,
  40952. configurable: true
  40953. });
  40954. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40955. /**
  40956. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40957. * @return Frame time variance in milliseconds squared
  40958. */
  40959. get: function () {
  40960. return this._rollingFrameTime.variance;
  40961. },
  40962. enumerable: true,
  40963. configurable: true
  40964. });
  40965. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40966. /**
  40967. * Returns the frame time of the most recent frame
  40968. * @return Frame time in milliseconds
  40969. */
  40970. get: function () {
  40971. return this._rollingFrameTime.history(0);
  40972. },
  40973. enumerable: true,
  40974. configurable: true
  40975. });
  40976. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40977. /**
  40978. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40979. * @return Framerate in frames per second
  40980. */
  40981. get: function () {
  40982. return 1000.0 / this._rollingFrameTime.average;
  40983. },
  40984. enumerable: true,
  40985. configurable: true
  40986. });
  40987. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40988. /**
  40989. * Returns the average framerate in frames per second using the most recent frame time
  40990. * @return Framerate in frames per second
  40991. */
  40992. get: function () {
  40993. var history = this._rollingFrameTime.history(0);
  40994. if (history === 0) {
  40995. return 0;
  40996. }
  40997. return 1000.0 / history;
  40998. },
  40999. enumerable: true,
  41000. configurable: true
  41001. });
  41002. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41003. /**
  41004. * Returns true if enough samples have been taken to completely fill the sliding window
  41005. * @return true if saturated
  41006. */
  41007. get: function () {
  41008. return this._rollingFrameTime.isSaturated();
  41009. },
  41010. enumerable: true,
  41011. configurable: true
  41012. });
  41013. /**
  41014. * Enables contributions to the sliding window sample set
  41015. */
  41016. PerformanceMonitor.prototype.enable = function () {
  41017. this._enabled = true;
  41018. };
  41019. /**
  41020. * Disables contributions to the sliding window sample set
  41021. * Samples will not be interpolated over the disabled period
  41022. */
  41023. PerformanceMonitor.prototype.disable = function () {
  41024. this._enabled = false;
  41025. //clear last sample to avoid interpolating over the disabled period when next enabled
  41026. this._lastFrameTimeMs = null;
  41027. };
  41028. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41029. /**
  41030. * Returns true if sampling is enabled
  41031. * @return true if enabled
  41032. */
  41033. get: function () {
  41034. return this._enabled;
  41035. },
  41036. enumerable: true,
  41037. configurable: true
  41038. });
  41039. /**
  41040. * Resets performance monitor
  41041. */
  41042. PerformanceMonitor.prototype.reset = function () {
  41043. //clear last sample to avoid interpolating over the disabled period when next enabled
  41044. this._lastFrameTimeMs = null;
  41045. //wipe record
  41046. this._rollingFrameTime.reset();
  41047. };
  41048. return PerformanceMonitor;
  41049. }());
  41050. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41051. /**
  41052. * RollingAverage
  41053. *
  41054. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41055. */
  41056. var RollingAverage = /** @class */ (function () {
  41057. /**
  41058. * constructor
  41059. * @param length The number of samples required to saturate the sliding window
  41060. */
  41061. function RollingAverage(length) {
  41062. this._samples = new Array(length);
  41063. this.reset();
  41064. }
  41065. /**
  41066. * Adds a sample to the sample set
  41067. * @param v The sample value
  41068. */
  41069. RollingAverage.prototype.add = function (v) {
  41070. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41071. var delta;
  41072. //we need to check if we've already wrapped round
  41073. if (this.isSaturated()) {
  41074. //remove bottom of stack from mean
  41075. var bottomValue = this._samples[this._pos];
  41076. delta = bottomValue - this.average;
  41077. this.average -= delta / (this._sampleCount - 1);
  41078. this._m2 -= delta * (bottomValue - this.average);
  41079. }
  41080. else {
  41081. this._sampleCount++;
  41082. }
  41083. //add new value to mean
  41084. delta = v - this.average;
  41085. this.average += delta / (this._sampleCount);
  41086. this._m2 += delta * (v - this.average);
  41087. //set the new variance
  41088. this.variance = this._m2 / (this._sampleCount - 1);
  41089. this._samples[this._pos] = v;
  41090. this._pos++;
  41091. this._pos %= this._samples.length; //positive wrap around
  41092. };
  41093. /**
  41094. * Returns previously added values or null if outside of history or outside the sliding window domain
  41095. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41096. * @return Value previously recorded with add() or null if outside of range
  41097. */
  41098. RollingAverage.prototype.history = function (i) {
  41099. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41100. return 0;
  41101. }
  41102. var i0 = this._wrapPosition(this._pos - 1.0);
  41103. return this._samples[this._wrapPosition(i0 - i)];
  41104. };
  41105. /**
  41106. * Returns true if enough samples have been taken to completely fill the sliding window
  41107. * @return true if sample-set saturated
  41108. */
  41109. RollingAverage.prototype.isSaturated = function () {
  41110. return this._sampleCount >= this._samples.length;
  41111. };
  41112. /**
  41113. * Resets the rolling average (equivalent to 0 samples taken so far)
  41114. */
  41115. RollingAverage.prototype.reset = function () {
  41116. this.average = 0;
  41117. this.variance = 0;
  41118. this._sampleCount = 0;
  41119. this._pos = 0;
  41120. this._m2 = 0;
  41121. };
  41122. /**
  41123. * Wraps a value around the sample range boundaries
  41124. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41125. * @return Wrapped position in sample range
  41126. */
  41127. RollingAverage.prototype._wrapPosition = function (i) {
  41128. var max = this._samples.length;
  41129. return ((i % max) + max) % max;
  41130. };
  41131. return RollingAverage;
  41132. }());
  41133. BABYLON.RollingAverage = RollingAverage;
  41134. })(BABYLON || (BABYLON = {}));
  41135. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41136. var BABYLON;
  41137. (function (BABYLON) {
  41138. /**
  41139. * "Static Class" containing the most commonly used helper while dealing with material for
  41140. * rendering purpose.
  41141. *
  41142. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41143. *
  41144. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41145. */
  41146. var MaterialHelper = /** @class */ (function () {
  41147. function MaterialHelper() {
  41148. }
  41149. /**
  41150. * Bind the current view position to an effect.
  41151. * @param effect The effect to be bound
  41152. * @param scene The scene the eyes position is used from
  41153. */
  41154. MaterialHelper.BindEyePosition = function (effect, scene) {
  41155. if (scene._forcedViewPosition) {
  41156. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41157. return;
  41158. }
  41159. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41160. };
  41161. /**
  41162. * Helps preparing the defines values about the UVs in used in the effect.
  41163. * UVs are shared as much as we can accross chanels in the shaders.
  41164. * @param texture The texture we are preparing the UVs for
  41165. * @param defines The defines to update
  41166. * @param key The chanel key "diffuse", "specular"... used in the shader
  41167. */
  41168. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41169. defines._needUVs = true;
  41170. defines[key] = true;
  41171. if (texture.getTextureMatrix().isIdentity(true)) {
  41172. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41173. if (texture.coordinatesIndex === 0) {
  41174. defines["MAINUV1"] = true;
  41175. }
  41176. else {
  41177. defines["MAINUV2"] = true;
  41178. }
  41179. }
  41180. else {
  41181. defines[key + "DIRECTUV"] = 0;
  41182. }
  41183. };
  41184. /**
  41185. * Binds a texture matrix value to its corrsponding uniform
  41186. * @param texture The texture to bind the matrix for
  41187. * @param uniformBuffer The uniform buffer receivin the data
  41188. * @param key The chanel key "diffuse", "specular"... used in the shader
  41189. */
  41190. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41191. var matrix = texture.getTextureMatrix();
  41192. if (!matrix.isIdentity(true)) {
  41193. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41194. }
  41195. };
  41196. /**
  41197. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41198. * @param mesh defines the current mesh
  41199. * @param scene defines the current scene
  41200. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41201. * @param pointsCloud defines if point cloud rendering has to be turned on
  41202. * @param fogEnabled defines if fog has to be turned on
  41203. * @param alphaTest defines if alpha testing has to be turned on
  41204. * @param defines defines the current list of defines
  41205. */
  41206. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41207. if (defines._areMiscDirty) {
  41208. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41209. defines["POINTSIZE"] = pointsCloud;
  41210. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41211. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41212. defines["ALPHATEST"] = alphaTest;
  41213. }
  41214. };
  41215. /**
  41216. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41217. * @param scene defines the current scene
  41218. * @param engine defines the current engine
  41219. * @param defines specifies the list of active defines
  41220. * @param useInstances defines if instances have to be turned on
  41221. * @param useClipPlane defines if clip plane have to be turned on
  41222. */
  41223. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41224. if (useClipPlane === void 0) { useClipPlane = null; }
  41225. var changed = false;
  41226. if (useClipPlane == null) {
  41227. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41228. }
  41229. if (defines["CLIPPLANE"] !== useClipPlane) {
  41230. defines["CLIPPLANE"] = useClipPlane;
  41231. changed = true;
  41232. }
  41233. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41234. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41235. changed = true;
  41236. }
  41237. if (defines["INSTANCES"] !== useInstances) {
  41238. defines["INSTANCES"] = useInstances;
  41239. changed = true;
  41240. }
  41241. if (changed) {
  41242. defines.markAsUnprocessed();
  41243. }
  41244. };
  41245. /**
  41246. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41247. * @param mesh The mesh containing the geometry data we will draw
  41248. * @param defines The defines to update
  41249. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41250. * @param useBones Precise whether bones should be used or not (override mesh info)
  41251. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41252. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41253. * @returns false if defines are considered not dirty and have not been checked
  41254. */
  41255. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41256. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41257. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41258. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41259. return false;
  41260. }
  41261. defines._normals = defines._needNormals;
  41262. defines._uvs = defines._needUVs;
  41263. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41264. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41265. defines["TANGENT"] = true;
  41266. }
  41267. if (defines._needUVs) {
  41268. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41269. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41270. }
  41271. else {
  41272. defines["UV1"] = false;
  41273. defines["UV2"] = false;
  41274. }
  41275. if (useVertexColor) {
  41276. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41277. defines["VERTEXCOLOR"] = hasVertexColors;
  41278. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41279. }
  41280. if (useBones) {
  41281. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41282. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41283. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41284. }
  41285. else {
  41286. defines["NUM_BONE_INFLUENCERS"] = 0;
  41287. defines["BonesPerMesh"] = 0;
  41288. }
  41289. }
  41290. if (useMorphTargets) {
  41291. var manager = mesh.morphTargetManager;
  41292. if (manager) {
  41293. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41294. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41295. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41296. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41297. }
  41298. else {
  41299. defines["MORPHTARGETS_TANGENT"] = false;
  41300. defines["MORPHTARGETS_NORMAL"] = false;
  41301. defines["MORPHTARGETS"] = false;
  41302. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41303. }
  41304. }
  41305. return true;
  41306. };
  41307. /**
  41308. * Prepares the defines related to the light information passed in parameter
  41309. * @param scene The scene we are intending to draw
  41310. * @param mesh The mesh the effect is compiling for
  41311. * @param defines The defines to update
  41312. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41313. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41314. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41315. * @returns true if normals will be required for the rest of the effect
  41316. */
  41317. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41318. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41319. if (disableLighting === void 0) { disableLighting = false; }
  41320. if (!defines._areLightsDirty) {
  41321. return defines._needNormals;
  41322. }
  41323. var lightIndex = 0;
  41324. var needNormals = false;
  41325. var needRebuild = false;
  41326. var lightmapMode = false;
  41327. var shadowEnabled = false;
  41328. var specularEnabled = false;
  41329. if (scene.lightsEnabled && !disableLighting) {
  41330. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41331. var light = _a[_i];
  41332. needNormals = true;
  41333. if (defines["LIGHT" + lightIndex] === undefined) {
  41334. needRebuild = true;
  41335. }
  41336. defines["LIGHT" + lightIndex] = true;
  41337. defines["SPOTLIGHT" + lightIndex] = false;
  41338. defines["HEMILIGHT" + lightIndex] = false;
  41339. defines["POINTLIGHT" + lightIndex] = false;
  41340. defines["DIRLIGHT" + lightIndex] = false;
  41341. var type;
  41342. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41343. type = "SPOTLIGHT" + lightIndex;
  41344. var spotLight = light;
  41345. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41346. }
  41347. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41348. type = "HEMILIGHT" + lightIndex;
  41349. }
  41350. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41351. type = "POINTLIGHT" + lightIndex;
  41352. }
  41353. else {
  41354. type = "DIRLIGHT" + lightIndex;
  41355. }
  41356. defines[type] = true;
  41357. // Specular
  41358. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41359. specularEnabled = true;
  41360. }
  41361. // Shadows
  41362. defines["SHADOW" + lightIndex] = false;
  41363. defines["SHADOWPCF" + lightIndex] = false;
  41364. defines["SHADOWPCSS" + lightIndex] = false;
  41365. defines["SHADOWPOISSON" + lightIndex] = false;
  41366. defines["SHADOWESM" + lightIndex] = false;
  41367. defines["SHADOWCUBE" + lightIndex] = false;
  41368. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41369. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41370. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41371. var shadowGenerator = light.getShadowGenerator();
  41372. if (shadowGenerator) {
  41373. shadowEnabled = true;
  41374. shadowGenerator.prepareDefines(defines, lightIndex);
  41375. }
  41376. }
  41377. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41378. lightmapMode = true;
  41379. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41380. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41381. }
  41382. else {
  41383. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41384. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41385. }
  41386. lightIndex++;
  41387. if (lightIndex === maxSimultaneousLights)
  41388. break;
  41389. }
  41390. }
  41391. defines["SPECULARTERM"] = specularEnabled;
  41392. defines["SHADOWS"] = shadowEnabled;
  41393. // Resetting all other lights if any
  41394. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41395. if (defines["LIGHT" + index] !== undefined) {
  41396. defines["LIGHT" + index] = false;
  41397. defines["HEMILIGHT" + lightIndex] = false;
  41398. defines["POINTLIGHT" + lightIndex] = false;
  41399. defines["DIRLIGHT" + lightIndex] = false;
  41400. defines["SPOTLIGHT" + lightIndex] = false;
  41401. defines["SHADOW" + lightIndex] = false;
  41402. }
  41403. }
  41404. var caps = scene.getEngine().getCaps();
  41405. if (defines["SHADOWFLOAT"] === undefined) {
  41406. needRebuild = true;
  41407. }
  41408. defines["SHADOWFLOAT"] = shadowEnabled &&
  41409. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41410. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41411. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41412. if (needRebuild) {
  41413. defines.rebuild();
  41414. }
  41415. return needNormals;
  41416. };
  41417. /**
  41418. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41419. * that won t be acctive due to defines being turned off.
  41420. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41421. * @param samplersList The samplers list
  41422. * @param defines The defines helping in the list generation
  41423. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41424. */
  41425. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41426. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41427. var uniformsList;
  41428. var uniformBuffersList = null;
  41429. if (uniformsListOrOptions.uniformsNames) {
  41430. var options = uniformsListOrOptions;
  41431. uniformsList = options.uniformsNames;
  41432. uniformBuffersList = options.uniformBuffersNames;
  41433. samplersList = options.samplers;
  41434. defines = options.defines;
  41435. maxSimultaneousLights = options.maxSimultaneousLights;
  41436. }
  41437. else {
  41438. uniformsList = uniformsListOrOptions;
  41439. if (!samplersList) {
  41440. samplersList = [];
  41441. }
  41442. }
  41443. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41444. if (!defines["LIGHT" + lightIndex]) {
  41445. break;
  41446. }
  41447. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41448. if (uniformBuffersList) {
  41449. uniformBuffersList.push("Light" + lightIndex);
  41450. }
  41451. samplersList.push("shadowSampler" + lightIndex);
  41452. samplersList.push("depthSampler" + lightIndex);
  41453. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41454. samplersList.push("projectionLightSampler" + lightIndex);
  41455. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41456. }
  41457. }
  41458. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41459. uniformsList.push("morphTargetInfluences");
  41460. }
  41461. };
  41462. /**
  41463. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41464. * @param defines The defines to update while falling back
  41465. * @param fallbacks The authorized effect fallbacks
  41466. * @param maxSimultaneousLights The maximum number of lights allowed
  41467. * @param rank the current rank of the Effect
  41468. * @returns The newly affected rank
  41469. */
  41470. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41471. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41472. if (rank === void 0) { rank = 0; }
  41473. var lightFallbackRank = 0;
  41474. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41475. if (!defines["LIGHT" + lightIndex]) {
  41476. break;
  41477. }
  41478. if (lightIndex > 0) {
  41479. lightFallbackRank = rank + lightIndex;
  41480. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41481. }
  41482. if (!defines["SHADOWS"]) {
  41483. if (defines["SHADOW" + lightIndex]) {
  41484. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41485. }
  41486. if (defines["SHADOWPCF" + lightIndex]) {
  41487. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41488. }
  41489. if (defines["SHADOWPCSS" + lightIndex]) {
  41490. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41491. }
  41492. if (defines["SHADOWPOISSON" + lightIndex]) {
  41493. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41494. }
  41495. if (defines["SHADOWESM" + lightIndex]) {
  41496. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41497. }
  41498. }
  41499. }
  41500. return lightFallbackRank++;
  41501. };
  41502. /**
  41503. * Prepares the list of attributes required for morph targets according to the effect defines.
  41504. * @param attribs The current list of supported attribs
  41505. * @param mesh The mesh to prepare the morph targets attributes for
  41506. * @param defines The current Defines of the effect
  41507. */
  41508. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41509. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41510. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41511. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41512. var manager = mesh.morphTargetManager;
  41513. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41514. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41515. for (var index = 0; index < influencers; index++) {
  41516. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41517. if (normal) {
  41518. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41519. }
  41520. if (tangent) {
  41521. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41522. }
  41523. if (attribs.length > maxAttributesCount) {
  41524. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41525. }
  41526. }
  41527. }
  41528. };
  41529. /**
  41530. * Prepares the list of attributes required for bones according to the effect defines.
  41531. * @param attribs The current list of supported attribs
  41532. * @param mesh The mesh to prepare the bones attributes for
  41533. * @param defines The current Defines of the effect
  41534. * @param fallbacks The current efffect fallback strategy
  41535. */
  41536. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41537. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41538. fallbacks.addCPUSkinningFallback(0, mesh);
  41539. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41540. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41541. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41542. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41543. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41544. }
  41545. }
  41546. };
  41547. /**
  41548. * Prepares the list of attributes required for instances according to the effect defines.
  41549. * @param attribs The current list of supported attribs
  41550. * @param defines The current Defines of the effect
  41551. */
  41552. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41553. if (defines["INSTANCES"]) {
  41554. attribs.push("world0");
  41555. attribs.push("world1");
  41556. attribs.push("world2");
  41557. attribs.push("world3");
  41558. }
  41559. };
  41560. /**
  41561. * Binds the light shadow information to the effect for the given mesh.
  41562. * @param light The light containing the generator
  41563. * @param scene The scene the lights belongs to
  41564. * @param mesh The mesh we are binding the information to render
  41565. * @param lightIndex The light index in the effect used to render the mesh
  41566. * @param effect The effect we are binding the data to
  41567. */
  41568. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41569. if (light.shadowEnabled && mesh.receiveShadows) {
  41570. var shadowGenerator = light.getShadowGenerator();
  41571. if (shadowGenerator) {
  41572. shadowGenerator.bindShadowLight(lightIndex, effect);
  41573. }
  41574. }
  41575. };
  41576. /**
  41577. * Binds the light information to the effect.
  41578. * @param light The light containing the generator
  41579. * @param effect The effect we are binding the data to
  41580. * @param lightIndex The light index in the effect used to render
  41581. */
  41582. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41583. light.transferToEffect(effect, lightIndex + "");
  41584. };
  41585. /**
  41586. * Binds the lights information from the scene to the effect for the given mesh.
  41587. * @param scene The scene the lights belongs to
  41588. * @param mesh The mesh we are binding the information to render
  41589. * @param effect The effect we are binding the data to
  41590. * @param defines The generated defines for the effect
  41591. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41592. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41593. */
  41594. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41595. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41596. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41597. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41598. for (var i = 0; i < len; i++) {
  41599. var light = mesh._lightSources[i];
  41600. var iAsString = i.toString();
  41601. var scaledIntensity = light.getScaledIntensity();
  41602. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41603. MaterialHelper.BindLightProperties(light, effect, i);
  41604. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41605. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41606. if (defines["SPECULARTERM"]) {
  41607. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41608. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41609. }
  41610. // Shadows
  41611. if (scene.shadowsEnabled) {
  41612. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41613. }
  41614. light._uniformBuffer.update();
  41615. }
  41616. };
  41617. /**
  41618. * Binds the fog information from the scene to the effect for the given mesh.
  41619. * @param scene The scene the lights belongs to
  41620. * @param mesh The mesh we are binding the information to render
  41621. * @param effect The effect we are binding the data to
  41622. */
  41623. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41624. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41625. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41626. effect.setColor3("vFogColor", scene.fogColor);
  41627. }
  41628. };
  41629. /**
  41630. * Binds the bones information from the mesh to the effect.
  41631. * @param mesh The mesh we are binding the information to render
  41632. * @param effect The effect we are binding the data to
  41633. */
  41634. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41635. if (!effect || !mesh) {
  41636. return;
  41637. }
  41638. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41639. mesh.computeBonesUsingShaders = false;
  41640. }
  41641. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41642. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41643. if (matrices) {
  41644. effect.setMatrices("mBones", matrices);
  41645. }
  41646. }
  41647. };
  41648. /**
  41649. * Binds the morph targets information from the mesh to the effect.
  41650. * @param abstractMesh The mesh we are binding the information to render
  41651. * @param effect The effect we are binding the data to
  41652. */
  41653. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41654. var manager = abstractMesh.morphTargetManager;
  41655. if (!abstractMesh || !manager) {
  41656. return;
  41657. }
  41658. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41659. };
  41660. /**
  41661. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41662. * @param defines The generated defines used in the effect
  41663. * @param effect The effect we are binding the data to
  41664. * @param scene The scene we are willing to render with logarithmic scale for
  41665. */
  41666. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41667. if (defines["LOGARITHMICDEPTH"]) {
  41668. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41669. }
  41670. };
  41671. /**
  41672. * Binds the clip plane information from the scene to the effect.
  41673. * @param scene The scene the clip plane information are extracted from
  41674. * @param effect The effect we are binding the data to
  41675. */
  41676. MaterialHelper.BindClipPlane = function (effect, scene) {
  41677. if (scene.clipPlane) {
  41678. var clipPlane = scene.clipPlane;
  41679. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41680. }
  41681. };
  41682. return MaterialHelper;
  41683. }());
  41684. BABYLON.MaterialHelper = MaterialHelper;
  41685. })(BABYLON || (BABYLON = {}));
  41686. //# sourceMappingURL=babylon.materialHelper.js.map
  41687. var BABYLON;
  41688. (function (BABYLON) {
  41689. var PushMaterial = /** @class */ (function (_super) {
  41690. __extends(PushMaterial, _super);
  41691. function PushMaterial(name, scene) {
  41692. var _this = _super.call(this, name, scene) || this;
  41693. _this._normalMatrix = new BABYLON.Matrix();
  41694. _this.storeEffectOnSubMeshes = true;
  41695. return _this;
  41696. }
  41697. PushMaterial.prototype.getEffect = function () {
  41698. return this._activeEffect;
  41699. };
  41700. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41701. if (!mesh) {
  41702. return false;
  41703. }
  41704. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41705. return true;
  41706. }
  41707. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41708. };
  41709. /**
  41710. * Binds the given world matrix to the active effect
  41711. *
  41712. * @param world the matrix to bind
  41713. */
  41714. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41715. this._activeEffect.setMatrix("world", world);
  41716. };
  41717. /**
  41718. * Binds the given normal matrix to the active effect
  41719. *
  41720. * @param normalMatrix the matrix to bind
  41721. */
  41722. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41723. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41724. };
  41725. PushMaterial.prototype.bind = function (world, mesh) {
  41726. if (!mesh) {
  41727. return;
  41728. }
  41729. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41730. };
  41731. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41732. if (effect === void 0) { effect = null; }
  41733. _super.prototype._afterBind.call(this, mesh);
  41734. this.getScene()._cachedEffect = effect;
  41735. };
  41736. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41737. if (visibility === void 0) { visibility = 1; }
  41738. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41739. };
  41740. return PushMaterial;
  41741. }(BABYLON.Material));
  41742. BABYLON.PushMaterial = PushMaterial;
  41743. })(BABYLON || (BABYLON = {}));
  41744. //# sourceMappingURL=babylon.pushMaterial.js.map
  41745. var BABYLON;
  41746. (function (BABYLON) {
  41747. /** @hidden */
  41748. var StandardMaterialDefines = /** @class */ (function (_super) {
  41749. __extends(StandardMaterialDefines, _super);
  41750. function StandardMaterialDefines() {
  41751. var _this = _super.call(this) || this;
  41752. _this.MAINUV1 = false;
  41753. _this.MAINUV2 = false;
  41754. _this.DIFFUSE = false;
  41755. _this.DIFFUSEDIRECTUV = 0;
  41756. _this.AMBIENT = false;
  41757. _this.AMBIENTDIRECTUV = 0;
  41758. _this.OPACITY = false;
  41759. _this.OPACITYDIRECTUV = 0;
  41760. _this.OPACITYRGB = false;
  41761. _this.REFLECTION = false;
  41762. _this.EMISSIVE = false;
  41763. _this.EMISSIVEDIRECTUV = 0;
  41764. _this.SPECULAR = false;
  41765. _this.SPECULARDIRECTUV = 0;
  41766. _this.BUMP = false;
  41767. _this.BUMPDIRECTUV = 0;
  41768. _this.PARALLAX = false;
  41769. _this.PARALLAXOCCLUSION = false;
  41770. _this.SPECULAROVERALPHA = false;
  41771. _this.CLIPPLANE = false;
  41772. _this.ALPHATEST = false;
  41773. _this.DEPTHPREPASS = false;
  41774. _this.ALPHAFROMDIFFUSE = false;
  41775. _this.POINTSIZE = false;
  41776. _this.FOG = false;
  41777. _this.SPECULARTERM = false;
  41778. _this.DIFFUSEFRESNEL = false;
  41779. _this.OPACITYFRESNEL = false;
  41780. _this.REFLECTIONFRESNEL = false;
  41781. _this.REFRACTIONFRESNEL = false;
  41782. _this.EMISSIVEFRESNEL = false;
  41783. _this.FRESNEL = false;
  41784. _this.NORMAL = false;
  41785. _this.UV1 = false;
  41786. _this.UV2 = false;
  41787. _this.VERTEXCOLOR = false;
  41788. _this.VERTEXALPHA = false;
  41789. _this.NUM_BONE_INFLUENCERS = 0;
  41790. _this.BonesPerMesh = 0;
  41791. _this.INSTANCES = false;
  41792. _this.GLOSSINESS = false;
  41793. _this.ROUGHNESS = false;
  41794. _this.EMISSIVEASILLUMINATION = false;
  41795. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41796. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41797. _this.LIGHTMAP = false;
  41798. _this.LIGHTMAPDIRECTUV = 0;
  41799. _this.OBJECTSPACE_NORMALMAP = false;
  41800. _this.USELIGHTMAPASSHADOWMAP = false;
  41801. _this.REFLECTIONMAP_3D = false;
  41802. _this.REFLECTIONMAP_SPHERICAL = false;
  41803. _this.REFLECTIONMAP_PLANAR = false;
  41804. _this.REFLECTIONMAP_CUBIC = false;
  41805. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41806. _this.REFLECTIONMAP_PROJECTION = false;
  41807. _this.REFLECTIONMAP_SKYBOX = false;
  41808. _this.REFLECTIONMAP_EXPLICIT = false;
  41809. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41810. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41811. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41812. _this.INVERTCUBICMAP = false;
  41813. _this.LOGARITHMICDEPTH = false;
  41814. _this.REFRACTION = false;
  41815. _this.REFRACTIONMAP_3D = false;
  41816. _this.REFLECTIONOVERALPHA = false;
  41817. _this.TWOSIDEDLIGHTING = false;
  41818. _this.SHADOWFLOAT = false;
  41819. _this.MORPHTARGETS = false;
  41820. _this.MORPHTARGETS_NORMAL = false;
  41821. _this.MORPHTARGETS_TANGENT = false;
  41822. _this.NUM_MORPH_INFLUENCERS = 0;
  41823. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41824. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41825. _this.IMAGEPROCESSING = false;
  41826. _this.VIGNETTE = false;
  41827. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41828. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41829. _this.TONEMAPPING = false;
  41830. _this.CONTRAST = false;
  41831. _this.COLORCURVES = false;
  41832. _this.COLORGRADING = false;
  41833. _this.COLORGRADING3D = false;
  41834. _this.SAMPLER3DGREENDEPTH = false;
  41835. _this.SAMPLER3DBGRMAP = false;
  41836. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41837. /**
  41838. * If the reflection texture on this material is in linear color space
  41839. * @hidden
  41840. */
  41841. _this.IS_REFLECTION_LINEAR = false;
  41842. /**
  41843. * If the refraction texture on this material is in linear color space
  41844. * @hidden
  41845. */
  41846. _this.IS_REFRACTION_LINEAR = false;
  41847. _this.EXPOSURE = false;
  41848. _this.rebuild();
  41849. return _this;
  41850. }
  41851. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41852. var modes = [
  41853. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41854. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41855. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41856. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41857. ];
  41858. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41859. var mode = modes_1[_i];
  41860. this[mode] = (mode === modeToEnable);
  41861. }
  41862. };
  41863. return StandardMaterialDefines;
  41864. }(BABYLON.MaterialDefines));
  41865. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41866. var StandardMaterial = /** @class */ (function (_super) {
  41867. __extends(StandardMaterial, _super);
  41868. function StandardMaterial(name, scene) {
  41869. var _this = _super.call(this, name, scene) || this;
  41870. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41871. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41872. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41873. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41874. _this.specularPower = 64;
  41875. _this._useAlphaFromDiffuseTexture = false;
  41876. _this._useEmissiveAsIllumination = false;
  41877. _this._linkEmissiveWithDiffuse = false;
  41878. _this._useSpecularOverAlpha = false;
  41879. _this._useReflectionOverAlpha = false;
  41880. _this._disableLighting = false;
  41881. _this._useObjectSpaceNormalMap = false;
  41882. _this._useParallax = false;
  41883. _this._useParallaxOcclusion = false;
  41884. _this.parallaxScaleBias = 0.05;
  41885. _this._roughness = 0;
  41886. _this.indexOfRefraction = 0.98;
  41887. _this.invertRefractionY = true;
  41888. /**
  41889. * Defines the alpha limits in alpha test mode
  41890. */
  41891. _this.alphaCutOff = 0.4;
  41892. _this._useLightmapAsShadowmap = false;
  41893. _this._useReflectionFresnelFromSpecular = false;
  41894. _this._useGlossinessFromSpecularMapAlpha = false;
  41895. _this._maxSimultaneousLights = 4;
  41896. /**
  41897. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41898. */
  41899. _this._invertNormalMapX = false;
  41900. /**
  41901. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41902. */
  41903. _this._invertNormalMapY = false;
  41904. /**
  41905. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41906. */
  41907. _this._twoSidedLighting = false;
  41908. _this._renderTargets = new BABYLON.SmartArray(16);
  41909. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41910. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41911. // Setup the default processing configuration to the scene.
  41912. _this._attachImageProcessingConfiguration(null);
  41913. _this.getRenderTargetTextures = function () {
  41914. _this._renderTargets.reset();
  41915. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41916. _this._renderTargets.push(_this._reflectionTexture);
  41917. }
  41918. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41919. _this._renderTargets.push(_this._refractionTexture);
  41920. }
  41921. return _this._renderTargets;
  41922. };
  41923. return _this;
  41924. }
  41925. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41926. /**
  41927. * Gets the image processing configuration used either in this material.
  41928. */
  41929. get: function () {
  41930. return this._imageProcessingConfiguration;
  41931. },
  41932. /**
  41933. * Sets the Default image processing configuration used either in the this material.
  41934. *
  41935. * If sets to null, the scene one is in use.
  41936. */
  41937. set: function (value) {
  41938. this._attachImageProcessingConfiguration(value);
  41939. // Ensure the effect will be rebuilt.
  41940. this._markAllSubMeshesAsTexturesDirty();
  41941. },
  41942. enumerable: true,
  41943. configurable: true
  41944. });
  41945. /**
  41946. * Attaches a new image processing configuration to the Standard Material.
  41947. * @param configuration
  41948. */
  41949. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41950. var _this = this;
  41951. if (configuration === this._imageProcessingConfiguration) {
  41952. return;
  41953. }
  41954. // Detaches observer.
  41955. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41956. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41957. }
  41958. // Pick the scene configuration if needed.
  41959. if (!configuration) {
  41960. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41961. }
  41962. else {
  41963. this._imageProcessingConfiguration = configuration;
  41964. }
  41965. // Attaches observer.
  41966. if (this._imageProcessingConfiguration) {
  41967. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41968. _this._markAllSubMeshesAsImageProcessingDirty();
  41969. });
  41970. }
  41971. };
  41972. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  41973. /**
  41974. * Gets wether the color curves effect is enabled.
  41975. */
  41976. get: function () {
  41977. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41978. },
  41979. /**
  41980. * Sets wether the color curves effect is enabled.
  41981. */
  41982. set: function (value) {
  41983. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41984. },
  41985. enumerable: true,
  41986. configurable: true
  41987. });
  41988. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  41989. /**
  41990. * Gets wether the color grading effect is enabled.
  41991. */
  41992. get: function () {
  41993. return this.imageProcessingConfiguration.colorGradingEnabled;
  41994. },
  41995. /**
  41996. * Gets wether the color grading effect is enabled.
  41997. */
  41998. set: function (value) {
  41999. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42000. },
  42001. enumerable: true,
  42002. configurable: true
  42003. });
  42004. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42005. /**
  42006. * Gets wether tonemapping is enabled or not.
  42007. */
  42008. get: function () {
  42009. return this._imageProcessingConfiguration.toneMappingEnabled;
  42010. },
  42011. /**
  42012. * Sets wether tonemapping is enabled or not
  42013. */
  42014. set: function (value) {
  42015. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42016. },
  42017. enumerable: true,
  42018. configurable: true
  42019. });
  42020. ;
  42021. ;
  42022. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42023. /**
  42024. * The camera exposure used on this material.
  42025. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42026. * This corresponds to a photographic exposure.
  42027. */
  42028. get: function () {
  42029. return this._imageProcessingConfiguration.exposure;
  42030. },
  42031. /**
  42032. * The camera exposure used on this material.
  42033. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42034. * This corresponds to a photographic exposure.
  42035. */
  42036. set: function (value) {
  42037. this._imageProcessingConfiguration.exposure = value;
  42038. },
  42039. enumerable: true,
  42040. configurable: true
  42041. });
  42042. ;
  42043. ;
  42044. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42045. /**
  42046. * Gets The camera contrast used on this material.
  42047. */
  42048. get: function () {
  42049. return this._imageProcessingConfiguration.contrast;
  42050. },
  42051. /**
  42052. * Sets The camera contrast used on this material.
  42053. */
  42054. set: function (value) {
  42055. this._imageProcessingConfiguration.contrast = value;
  42056. },
  42057. enumerable: true,
  42058. configurable: true
  42059. });
  42060. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42061. /**
  42062. * Gets the Color Grading 2D Lookup Texture.
  42063. */
  42064. get: function () {
  42065. return this._imageProcessingConfiguration.colorGradingTexture;
  42066. },
  42067. /**
  42068. * Sets the Color Grading 2D Lookup Texture.
  42069. */
  42070. set: function (value) {
  42071. this._imageProcessingConfiguration.colorGradingTexture = value;
  42072. },
  42073. enumerable: true,
  42074. configurable: true
  42075. });
  42076. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42077. /**
  42078. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42079. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42080. * 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;
  42081. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42082. */
  42083. get: function () {
  42084. return this._imageProcessingConfiguration.colorCurves;
  42085. },
  42086. /**
  42087. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42088. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42089. * 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;
  42090. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42091. */
  42092. set: function (value) {
  42093. this._imageProcessingConfiguration.colorCurves = value;
  42094. },
  42095. enumerable: true,
  42096. configurable: true
  42097. });
  42098. StandardMaterial.prototype.getClassName = function () {
  42099. return "StandardMaterial";
  42100. };
  42101. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42102. get: function () {
  42103. return this._useLogarithmicDepth;
  42104. },
  42105. set: function (value) {
  42106. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42107. this._markAllSubMeshesAsMiscDirty();
  42108. },
  42109. enumerable: true,
  42110. configurable: true
  42111. });
  42112. StandardMaterial.prototype.needAlphaBlending = function () {
  42113. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42114. };
  42115. StandardMaterial.prototype.needAlphaTesting = function () {
  42116. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42117. };
  42118. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42119. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42120. };
  42121. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42122. return this._diffuseTexture;
  42123. };
  42124. /**
  42125. * Child classes can use it to update shaders
  42126. */
  42127. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42128. if (useInstances === void 0) { useInstances = false; }
  42129. if (subMesh.effect && this.isFrozen) {
  42130. if (this._wasPreviouslyReady && subMesh.effect) {
  42131. return true;
  42132. }
  42133. }
  42134. if (!subMesh._materialDefines) {
  42135. subMesh._materialDefines = new StandardMaterialDefines();
  42136. }
  42137. var scene = this.getScene();
  42138. var defines = subMesh._materialDefines;
  42139. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42140. if (defines._renderId === scene.getRenderId()) {
  42141. return true;
  42142. }
  42143. }
  42144. var engine = scene.getEngine();
  42145. // Lights
  42146. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42147. // Textures
  42148. if (defines._areTexturesDirty) {
  42149. defines._needUVs = false;
  42150. defines.MAINUV1 = false;
  42151. defines.MAINUV2 = false;
  42152. if (scene.texturesEnabled) {
  42153. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42154. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42155. return false;
  42156. }
  42157. else {
  42158. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42159. }
  42160. }
  42161. else {
  42162. defines.DIFFUSE = false;
  42163. }
  42164. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42165. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42166. return false;
  42167. }
  42168. else {
  42169. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42170. }
  42171. }
  42172. else {
  42173. defines.AMBIENT = false;
  42174. }
  42175. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42176. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42177. return false;
  42178. }
  42179. else {
  42180. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42181. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42182. }
  42183. }
  42184. else {
  42185. defines.OPACITY = false;
  42186. }
  42187. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42188. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42189. return false;
  42190. }
  42191. else {
  42192. defines._needNormals = true;
  42193. defines.REFLECTION = true;
  42194. defines.ROUGHNESS = (this._roughness > 0);
  42195. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42196. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42197. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42198. switch (this._reflectionTexture.coordinatesMode) {
  42199. case BABYLON.Texture.EXPLICIT_MODE:
  42200. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42201. break;
  42202. case BABYLON.Texture.PLANAR_MODE:
  42203. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42204. break;
  42205. case BABYLON.Texture.PROJECTION_MODE:
  42206. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42207. break;
  42208. case BABYLON.Texture.SKYBOX_MODE:
  42209. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42210. break;
  42211. case BABYLON.Texture.SPHERICAL_MODE:
  42212. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42213. break;
  42214. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42215. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42216. break;
  42217. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42218. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42219. break;
  42220. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42221. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42222. break;
  42223. case BABYLON.Texture.CUBIC_MODE:
  42224. case BABYLON.Texture.INVCUBIC_MODE:
  42225. default:
  42226. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42227. break;
  42228. }
  42229. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42230. }
  42231. }
  42232. else {
  42233. defines.REFLECTION = false;
  42234. }
  42235. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42236. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42237. return false;
  42238. }
  42239. else {
  42240. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42241. }
  42242. }
  42243. else {
  42244. defines.EMISSIVE = false;
  42245. }
  42246. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42247. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42248. return false;
  42249. }
  42250. else {
  42251. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42252. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42253. }
  42254. }
  42255. else {
  42256. defines.LIGHTMAP = false;
  42257. }
  42258. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42259. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42260. return false;
  42261. }
  42262. else {
  42263. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42264. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42265. }
  42266. }
  42267. else {
  42268. defines.SPECULAR = false;
  42269. }
  42270. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42271. // Bump texure can not be not blocking.
  42272. if (!this._bumpTexture.isReady()) {
  42273. return false;
  42274. }
  42275. else {
  42276. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42277. defines.PARALLAX = this._useParallax;
  42278. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42279. }
  42280. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42281. }
  42282. else {
  42283. defines.BUMP = false;
  42284. }
  42285. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42286. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42287. return false;
  42288. }
  42289. else {
  42290. defines._needUVs = true;
  42291. defines.REFRACTION = true;
  42292. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42293. }
  42294. }
  42295. else {
  42296. defines.REFRACTION = false;
  42297. }
  42298. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42299. }
  42300. else {
  42301. defines.DIFFUSE = false;
  42302. defines.AMBIENT = false;
  42303. defines.OPACITY = false;
  42304. defines.REFLECTION = false;
  42305. defines.EMISSIVE = false;
  42306. defines.LIGHTMAP = false;
  42307. defines.BUMP = false;
  42308. defines.REFRACTION = false;
  42309. }
  42310. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42311. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42312. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42313. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42314. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42315. }
  42316. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42317. if (!this._imageProcessingConfiguration.isReady()) {
  42318. return false;
  42319. }
  42320. this._imageProcessingConfiguration.prepareDefines(defines);
  42321. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42322. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42323. }
  42324. if (defines._areFresnelDirty) {
  42325. if (StandardMaterial.FresnelEnabled) {
  42326. // Fresnel
  42327. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42328. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42329. this._reflectionFresnelParameters) {
  42330. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42331. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42332. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42333. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42334. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42335. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42336. defines._needNormals = true;
  42337. defines.FRESNEL = true;
  42338. }
  42339. }
  42340. else {
  42341. defines.FRESNEL = false;
  42342. }
  42343. }
  42344. // Misc.
  42345. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42346. // Attribs
  42347. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42348. // Values that need to be evaluated on every frame
  42349. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42350. // Get correct effect
  42351. if (defines.isDirty) {
  42352. defines.markAsProcessed();
  42353. scene.resetCachedMaterial();
  42354. // Fallbacks
  42355. var fallbacks = new BABYLON.EffectFallbacks();
  42356. if (defines.REFLECTION) {
  42357. fallbacks.addFallback(0, "REFLECTION");
  42358. }
  42359. if (defines.SPECULAR) {
  42360. fallbacks.addFallback(0, "SPECULAR");
  42361. }
  42362. if (defines.BUMP) {
  42363. fallbacks.addFallback(0, "BUMP");
  42364. }
  42365. if (defines.PARALLAX) {
  42366. fallbacks.addFallback(1, "PARALLAX");
  42367. }
  42368. if (defines.PARALLAXOCCLUSION) {
  42369. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42370. }
  42371. if (defines.SPECULAROVERALPHA) {
  42372. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42373. }
  42374. if (defines.FOG) {
  42375. fallbacks.addFallback(1, "FOG");
  42376. }
  42377. if (defines.POINTSIZE) {
  42378. fallbacks.addFallback(0, "POINTSIZE");
  42379. }
  42380. if (defines.LOGARITHMICDEPTH) {
  42381. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42382. }
  42383. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42384. if (defines.SPECULARTERM) {
  42385. fallbacks.addFallback(0, "SPECULARTERM");
  42386. }
  42387. if (defines.DIFFUSEFRESNEL) {
  42388. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42389. }
  42390. if (defines.OPACITYFRESNEL) {
  42391. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42392. }
  42393. if (defines.REFLECTIONFRESNEL) {
  42394. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42395. }
  42396. if (defines.EMISSIVEFRESNEL) {
  42397. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42398. }
  42399. if (defines.FRESNEL) {
  42400. fallbacks.addFallback(4, "FRESNEL");
  42401. }
  42402. //Attributes
  42403. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42404. if (defines.NORMAL) {
  42405. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42406. }
  42407. if (defines.UV1) {
  42408. attribs.push(BABYLON.VertexBuffer.UVKind);
  42409. }
  42410. if (defines.UV2) {
  42411. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42412. }
  42413. if (defines.VERTEXCOLOR) {
  42414. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42415. }
  42416. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42417. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42418. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42419. var shaderName = "default";
  42420. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42421. "vFogInfos", "vFogColor", "pointSize",
  42422. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42423. "mBones",
  42424. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42425. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42426. "vReflectionPosition", "vReflectionSize",
  42427. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42428. ];
  42429. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42430. var uniformBuffers = ["Material", "Scene"];
  42431. if (BABYLON.ImageProcessingConfiguration) {
  42432. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42433. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42434. }
  42435. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42436. uniformsNames: uniforms,
  42437. uniformBuffersNames: uniformBuffers,
  42438. samplers: samplers,
  42439. defines: defines,
  42440. maxSimultaneousLights: this._maxSimultaneousLights
  42441. });
  42442. if (this.customShaderNameResolve) {
  42443. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42444. }
  42445. var join = defines.toString();
  42446. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42447. attributes: attribs,
  42448. uniformsNames: uniforms,
  42449. uniformBuffersNames: uniformBuffers,
  42450. samplers: samplers,
  42451. defines: join,
  42452. fallbacks: fallbacks,
  42453. onCompiled: this.onCompiled,
  42454. onError: this.onError,
  42455. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42456. }, engine), defines);
  42457. this.buildUniformLayout();
  42458. }
  42459. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42460. return false;
  42461. }
  42462. defines._renderId = scene.getRenderId();
  42463. this._wasPreviouslyReady = true;
  42464. return true;
  42465. };
  42466. StandardMaterial.prototype.buildUniformLayout = function () {
  42467. // Order is important !
  42468. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42469. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42470. this._uniformBuffer.addUniform("opacityParts", 4);
  42471. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42472. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42473. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42474. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42475. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42476. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42477. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42478. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42479. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42480. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42481. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42482. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42483. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42484. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42485. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42486. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42487. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42488. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42489. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42490. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42491. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42492. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42493. this._uniformBuffer.addUniform("specularMatrix", 16);
  42494. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42495. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42496. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42497. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42498. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42499. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42500. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42501. this._uniformBuffer.addUniform("pointSize", 1);
  42502. this._uniformBuffer.create();
  42503. };
  42504. StandardMaterial.prototype.unbind = function () {
  42505. if (this._activeEffect) {
  42506. var needFlag = false;
  42507. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42508. this._activeEffect.setTexture("reflection2DSampler", null);
  42509. needFlag = true;
  42510. }
  42511. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42512. this._activeEffect.setTexture("refraction2DSampler", null);
  42513. needFlag = true;
  42514. }
  42515. if (needFlag) {
  42516. this._markAllSubMeshesAsTexturesDirty();
  42517. }
  42518. }
  42519. _super.prototype.unbind.call(this);
  42520. };
  42521. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42522. var scene = this.getScene();
  42523. var defines = subMesh._materialDefines;
  42524. if (!defines) {
  42525. return;
  42526. }
  42527. var effect = subMesh.effect;
  42528. if (!effect) {
  42529. return;
  42530. }
  42531. this._activeEffect = effect;
  42532. // Matrices
  42533. this.bindOnlyWorldMatrix(world);
  42534. // Normal Matrix
  42535. if (defines.OBJECTSPACE_NORMALMAP) {
  42536. world.toNormalMatrix(this._normalMatrix);
  42537. this.bindOnlyNormalMatrix(this._normalMatrix);
  42538. }
  42539. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42540. // Bones
  42541. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42542. if (mustRebind) {
  42543. this._uniformBuffer.bindToEffect(effect, "Material");
  42544. this.bindViewProjection(effect);
  42545. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42546. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42547. // Fresnel
  42548. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42549. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42550. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42551. }
  42552. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42553. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42554. }
  42555. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42556. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42557. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42558. }
  42559. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42560. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42561. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42562. }
  42563. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42564. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42565. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42566. }
  42567. }
  42568. // Textures
  42569. if (scene.texturesEnabled) {
  42570. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42571. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42572. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42573. if (this._diffuseTexture.hasAlpha) {
  42574. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42575. }
  42576. }
  42577. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42578. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42579. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42580. }
  42581. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42582. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42583. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42584. }
  42585. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42586. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42587. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42588. if (this._reflectionTexture.boundingBoxSize) {
  42589. var cubeTexture = this._reflectionTexture;
  42590. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42591. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42592. }
  42593. }
  42594. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42595. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42596. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42597. }
  42598. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42599. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42600. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42601. }
  42602. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42603. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42604. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42605. }
  42606. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42607. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42608. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42609. if (scene._mirroredCameraPosition) {
  42610. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42611. }
  42612. else {
  42613. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42614. }
  42615. }
  42616. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42617. var depth = 1.0;
  42618. if (!this._refractionTexture.isCube) {
  42619. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42620. if (this._refractionTexture.depth) {
  42621. depth = this._refractionTexture.depth;
  42622. }
  42623. }
  42624. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42625. }
  42626. }
  42627. // Point size
  42628. if (this.pointsCloud) {
  42629. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42630. }
  42631. if (defines.SPECULARTERM) {
  42632. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42633. }
  42634. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42635. // Diffuse
  42636. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42637. }
  42638. // Textures
  42639. if (scene.texturesEnabled) {
  42640. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42641. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42642. }
  42643. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42644. effect.setTexture("ambientSampler", this._ambientTexture);
  42645. }
  42646. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42647. effect.setTexture("opacitySampler", this._opacityTexture);
  42648. }
  42649. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42650. if (this._reflectionTexture.isCube) {
  42651. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42652. }
  42653. else {
  42654. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42655. }
  42656. }
  42657. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42658. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42659. }
  42660. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42661. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42662. }
  42663. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42664. effect.setTexture("specularSampler", this._specularTexture);
  42665. }
  42666. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42667. effect.setTexture("bumpSampler", this._bumpTexture);
  42668. }
  42669. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42670. var depth = 1.0;
  42671. if (this._refractionTexture.isCube) {
  42672. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42673. }
  42674. else {
  42675. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42676. }
  42677. }
  42678. }
  42679. // Clip plane
  42680. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42681. // Colors
  42682. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42683. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42684. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42685. }
  42686. if (mustRebind || !this.isFrozen) {
  42687. // Lights
  42688. if (scene.lightsEnabled && !this._disableLighting) {
  42689. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42690. }
  42691. // View
  42692. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42693. this.bindView(effect);
  42694. }
  42695. // Fog
  42696. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42697. // Morph targets
  42698. if (defines.NUM_MORPH_INFLUENCERS) {
  42699. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42700. }
  42701. // Log. depth
  42702. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42703. // image processing
  42704. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42705. this._imageProcessingConfiguration.bind(this._activeEffect);
  42706. }
  42707. }
  42708. this._uniformBuffer.update();
  42709. this._afterBind(mesh, this._activeEffect);
  42710. };
  42711. StandardMaterial.prototype.getAnimatables = function () {
  42712. var results = [];
  42713. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42714. results.push(this._diffuseTexture);
  42715. }
  42716. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42717. results.push(this._ambientTexture);
  42718. }
  42719. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42720. results.push(this._opacityTexture);
  42721. }
  42722. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42723. results.push(this._reflectionTexture);
  42724. }
  42725. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42726. results.push(this._emissiveTexture);
  42727. }
  42728. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42729. results.push(this._specularTexture);
  42730. }
  42731. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42732. results.push(this._bumpTexture);
  42733. }
  42734. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42735. results.push(this._lightmapTexture);
  42736. }
  42737. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42738. results.push(this._refractionTexture);
  42739. }
  42740. return results;
  42741. };
  42742. StandardMaterial.prototype.getActiveTextures = function () {
  42743. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42744. if (this._diffuseTexture) {
  42745. activeTextures.push(this._diffuseTexture);
  42746. }
  42747. if (this._ambientTexture) {
  42748. activeTextures.push(this._ambientTexture);
  42749. }
  42750. if (this._opacityTexture) {
  42751. activeTextures.push(this._opacityTexture);
  42752. }
  42753. if (this._reflectionTexture) {
  42754. activeTextures.push(this._reflectionTexture);
  42755. }
  42756. if (this._emissiveTexture) {
  42757. activeTextures.push(this._emissiveTexture);
  42758. }
  42759. if (this._specularTexture) {
  42760. activeTextures.push(this._specularTexture);
  42761. }
  42762. if (this._bumpTexture) {
  42763. activeTextures.push(this._bumpTexture);
  42764. }
  42765. if (this._lightmapTexture) {
  42766. activeTextures.push(this._lightmapTexture);
  42767. }
  42768. if (this._refractionTexture) {
  42769. activeTextures.push(this._refractionTexture);
  42770. }
  42771. return activeTextures;
  42772. };
  42773. StandardMaterial.prototype.hasTexture = function (texture) {
  42774. if (_super.prototype.hasTexture.call(this, texture)) {
  42775. return true;
  42776. }
  42777. if (this._diffuseTexture === texture) {
  42778. return true;
  42779. }
  42780. if (this._ambientTexture === texture) {
  42781. return true;
  42782. }
  42783. if (this._opacityTexture === texture) {
  42784. return true;
  42785. }
  42786. if (this._reflectionTexture === texture) {
  42787. return true;
  42788. }
  42789. if (this._emissiveTexture === texture) {
  42790. return true;
  42791. }
  42792. if (this._specularTexture === texture) {
  42793. return true;
  42794. }
  42795. if (this._bumpTexture === texture) {
  42796. return true;
  42797. }
  42798. if (this._lightmapTexture === texture) {
  42799. return true;
  42800. }
  42801. if (this._refractionTexture === texture) {
  42802. return true;
  42803. }
  42804. return false;
  42805. };
  42806. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42807. if (forceDisposeTextures) {
  42808. if (this._diffuseTexture) {
  42809. this._diffuseTexture.dispose();
  42810. }
  42811. if (this._ambientTexture) {
  42812. this._ambientTexture.dispose();
  42813. }
  42814. if (this._opacityTexture) {
  42815. this._opacityTexture.dispose();
  42816. }
  42817. if (this._reflectionTexture) {
  42818. this._reflectionTexture.dispose();
  42819. }
  42820. if (this._emissiveTexture) {
  42821. this._emissiveTexture.dispose();
  42822. }
  42823. if (this._specularTexture) {
  42824. this._specularTexture.dispose();
  42825. }
  42826. if (this._bumpTexture) {
  42827. this._bumpTexture.dispose();
  42828. }
  42829. if (this._lightmapTexture) {
  42830. this._lightmapTexture.dispose();
  42831. }
  42832. if (this._refractionTexture) {
  42833. this._refractionTexture.dispose();
  42834. }
  42835. }
  42836. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42837. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42838. }
  42839. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42840. };
  42841. StandardMaterial.prototype.clone = function (name) {
  42842. var _this = this;
  42843. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42844. result.name = name;
  42845. result.id = name;
  42846. return result;
  42847. };
  42848. StandardMaterial.prototype.serialize = function () {
  42849. return BABYLON.SerializationHelper.Serialize(this);
  42850. };
  42851. // Statics
  42852. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42853. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42854. };
  42855. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42856. get: function () {
  42857. return StandardMaterial._DiffuseTextureEnabled;
  42858. },
  42859. set: function (value) {
  42860. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42861. return;
  42862. }
  42863. StandardMaterial._DiffuseTextureEnabled = value;
  42864. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42865. },
  42866. enumerable: true,
  42867. configurable: true
  42868. });
  42869. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42870. get: function () {
  42871. return StandardMaterial._AmbientTextureEnabled;
  42872. },
  42873. set: function (value) {
  42874. if (StandardMaterial._AmbientTextureEnabled === value) {
  42875. return;
  42876. }
  42877. StandardMaterial._AmbientTextureEnabled = value;
  42878. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42879. },
  42880. enumerable: true,
  42881. configurable: true
  42882. });
  42883. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42884. get: function () {
  42885. return StandardMaterial._OpacityTextureEnabled;
  42886. },
  42887. set: function (value) {
  42888. if (StandardMaterial._OpacityTextureEnabled === value) {
  42889. return;
  42890. }
  42891. StandardMaterial._OpacityTextureEnabled = value;
  42892. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42893. },
  42894. enumerable: true,
  42895. configurable: true
  42896. });
  42897. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42898. get: function () {
  42899. return StandardMaterial._ReflectionTextureEnabled;
  42900. },
  42901. set: function (value) {
  42902. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42903. return;
  42904. }
  42905. StandardMaterial._ReflectionTextureEnabled = value;
  42906. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42907. },
  42908. enumerable: true,
  42909. configurable: true
  42910. });
  42911. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42912. get: function () {
  42913. return StandardMaterial._EmissiveTextureEnabled;
  42914. },
  42915. set: function (value) {
  42916. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42917. return;
  42918. }
  42919. StandardMaterial._EmissiveTextureEnabled = value;
  42920. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42921. },
  42922. enumerable: true,
  42923. configurable: true
  42924. });
  42925. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42926. get: function () {
  42927. return StandardMaterial._SpecularTextureEnabled;
  42928. },
  42929. set: function (value) {
  42930. if (StandardMaterial._SpecularTextureEnabled === value) {
  42931. return;
  42932. }
  42933. StandardMaterial._SpecularTextureEnabled = value;
  42934. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42935. },
  42936. enumerable: true,
  42937. configurable: true
  42938. });
  42939. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42940. get: function () {
  42941. return StandardMaterial._BumpTextureEnabled;
  42942. },
  42943. set: function (value) {
  42944. if (StandardMaterial._BumpTextureEnabled === value) {
  42945. return;
  42946. }
  42947. StandardMaterial._BumpTextureEnabled = value;
  42948. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42949. },
  42950. enumerable: true,
  42951. configurable: true
  42952. });
  42953. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42954. get: function () {
  42955. return StandardMaterial._LightmapTextureEnabled;
  42956. },
  42957. set: function (value) {
  42958. if (StandardMaterial._LightmapTextureEnabled === value) {
  42959. return;
  42960. }
  42961. StandardMaterial._LightmapTextureEnabled = value;
  42962. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42963. },
  42964. enumerable: true,
  42965. configurable: true
  42966. });
  42967. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  42968. get: function () {
  42969. return StandardMaterial._RefractionTextureEnabled;
  42970. },
  42971. set: function (value) {
  42972. if (StandardMaterial._RefractionTextureEnabled === value) {
  42973. return;
  42974. }
  42975. StandardMaterial._RefractionTextureEnabled = value;
  42976. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42977. },
  42978. enumerable: true,
  42979. configurable: true
  42980. });
  42981. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  42982. get: function () {
  42983. return StandardMaterial._ColorGradingTextureEnabled;
  42984. },
  42985. set: function (value) {
  42986. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  42987. return;
  42988. }
  42989. StandardMaterial._ColorGradingTextureEnabled = value;
  42990. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42991. },
  42992. enumerable: true,
  42993. configurable: true
  42994. });
  42995. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  42996. get: function () {
  42997. return StandardMaterial._FresnelEnabled;
  42998. },
  42999. set: function (value) {
  43000. if (StandardMaterial._FresnelEnabled === value) {
  43001. return;
  43002. }
  43003. StandardMaterial._FresnelEnabled = value;
  43004. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43005. },
  43006. enumerable: true,
  43007. configurable: true
  43008. });
  43009. // Flags used to enable or disable a type of texture for all Standard Materials
  43010. StandardMaterial._DiffuseTextureEnabled = true;
  43011. StandardMaterial._AmbientTextureEnabled = true;
  43012. StandardMaterial._OpacityTextureEnabled = true;
  43013. StandardMaterial._ReflectionTextureEnabled = true;
  43014. StandardMaterial._EmissiveTextureEnabled = true;
  43015. StandardMaterial._SpecularTextureEnabled = true;
  43016. StandardMaterial._BumpTextureEnabled = true;
  43017. StandardMaterial._LightmapTextureEnabled = true;
  43018. StandardMaterial._RefractionTextureEnabled = true;
  43019. StandardMaterial._ColorGradingTextureEnabled = true;
  43020. StandardMaterial._FresnelEnabled = true;
  43021. __decorate([
  43022. BABYLON.serializeAsTexture("diffuseTexture")
  43023. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43024. __decorate([
  43025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43026. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43027. __decorate([
  43028. BABYLON.serializeAsTexture("ambientTexture")
  43029. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43030. __decorate([
  43031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43032. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43033. __decorate([
  43034. BABYLON.serializeAsTexture("opacityTexture")
  43035. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43036. __decorate([
  43037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43038. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43039. __decorate([
  43040. BABYLON.serializeAsTexture("reflectionTexture")
  43041. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43042. __decorate([
  43043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43044. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43045. __decorate([
  43046. BABYLON.serializeAsTexture("emissiveTexture")
  43047. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43048. __decorate([
  43049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43050. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43051. __decorate([
  43052. BABYLON.serializeAsTexture("specularTexture")
  43053. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43054. __decorate([
  43055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43056. ], StandardMaterial.prototype, "specularTexture", void 0);
  43057. __decorate([
  43058. BABYLON.serializeAsTexture("bumpTexture")
  43059. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43060. __decorate([
  43061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43062. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43063. __decorate([
  43064. BABYLON.serializeAsTexture("lightmapTexture")
  43065. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43066. __decorate([
  43067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43068. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43069. __decorate([
  43070. BABYLON.serializeAsTexture("refractionTexture")
  43071. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43072. __decorate([
  43073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43074. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43075. __decorate([
  43076. BABYLON.serializeAsColor3("ambient")
  43077. ], StandardMaterial.prototype, "ambientColor", void 0);
  43078. __decorate([
  43079. BABYLON.serializeAsColor3("diffuse")
  43080. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43081. __decorate([
  43082. BABYLON.serializeAsColor3("specular")
  43083. ], StandardMaterial.prototype, "specularColor", void 0);
  43084. __decorate([
  43085. BABYLON.serializeAsColor3("emissive")
  43086. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43087. __decorate([
  43088. BABYLON.serialize()
  43089. ], StandardMaterial.prototype, "specularPower", void 0);
  43090. __decorate([
  43091. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43092. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43093. __decorate([
  43094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43095. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43096. __decorate([
  43097. BABYLON.serialize("useEmissiveAsIllumination")
  43098. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43099. __decorate([
  43100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43101. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43102. __decorate([
  43103. BABYLON.serialize("linkEmissiveWithDiffuse")
  43104. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43105. __decorate([
  43106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43107. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43108. __decorate([
  43109. BABYLON.serialize("useSpecularOverAlpha")
  43110. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43111. __decorate([
  43112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43113. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43114. __decorate([
  43115. BABYLON.serialize("useReflectionOverAlpha")
  43116. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43117. __decorate([
  43118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43119. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43120. __decorate([
  43121. BABYLON.serialize("disableLighting")
  43122. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43123. __decorate([
  43124. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43125. ], StandardMaterial.prototype, "disableLighting", void 0);
  43126. __decorate([
  43127. BABYLON.serialize("useObjectSpaceNormalMap")
  43128. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43129. __decorate([
  43130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43131. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43132. __decorate([
  43133. BABYLON.serialize("useParallax")
  43134. ], StandardMaterial.prototype, "_useParallax", void 0);
  43135. __decorate([
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43137. ], StandardMaterial.prototype, "useParallax", void 0);
  43138. __decorate([
  43139. BABYLON.serialize("useParallaxOcclusion")
  43140. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43141. __decorate([
  43142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43143. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43144. __decorate([
  43145. BABYLON.serialize()
  43146. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43147. __decorate([
  43148. BABYLON.serialize("roughness")
  43149. ], StandardMaterial.prototype, "_roughness", void 0);
  43150. __decorate([
  43151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43152. ], StandardMaterial.prototype, "roughness", void 0);
  43153. __decorate([
  43154. BABYLON.serialize()
  43155. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43156. __decorate([
  43157. BABYLON.serialize()
  43158. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43159. __decorate([
  43160. BABYLON.serialize()
  43161. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43162. __decorate([
  43163. BABYLON.serialize("useLightmapAsShadowmap")
  43164. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43165. __decorate([
  43166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43167. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43168. __decorate([
  43169. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43170. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43171. __decorate([
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43173. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43174. __decorate([
  43175. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43176. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43177. __decorate([
  43178. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43179. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43180. __decorate([
  43181. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43182. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43183. __decorate([
  43184. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43185. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43186. __decorate([
  43187. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43188. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43189. __decorate([
  43190. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43191. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43192. __decorate([
  43193. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43194. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43195. __decorate([
  43196. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43197. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43198. __decorate([
  43199. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43200. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43201. __decorate([
  43202. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43203. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43204. __decorate([
  43205. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43206. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43207. __decorate([
  43208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43209. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43210. __decorate([
  43211. BABYLON.serialize("maxSimultaneousLights")
  43212. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43213. __decorate([
  43214. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43215. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43216. __decorate([
  43217. BABYLON.serialize("invertNormalMapX")
  43218. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43219. __decorate([
  43220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43221. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43222. __decorate([
  43223. BABYLON.serialize("invertNormalMapY")
  43224. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43225. __decorate([
  43226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43227. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43228. __decorate([
  43229. BABYLON.serialize("twoSidedLighting")
  43230. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43231. __decorate([
  43232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43233. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43234. __decorate([
  43235. BABYLON.serialize()
  43236. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43237. return StandardMaterial;
  43238. }(BABYLON.PushMaterial));
  43239. BABYLON.StandardMaterial = StandardMaterial;
  43240. })(BABYLON || (BABYLON = {}));
  43241. //# sourceMappingURL=babylon.standardMaterial.js.map
  43242. var BABYLON;
  43243. (function (BABYLON) {
  43244. /**
  43245. * Manages the defines for the PBR Material.
  43246. * @hiddenChildren
  43247. */
  43248. var PBRMaterialDefines = /** @class */ (function (_super) {
  43249. __extends(PBRMaterialDefines, _super);
  43250. /**
  43251. * Initializes the PBR Material defines.
  43252. */
  43253. function PBRMaterialDefines() {
  43254. var _this = _super.call(this) || this;
  43255. _this.PBR = true;
  43256. _this.MAINUV1 = false;
  43257. _this.MAINUV2 = false;
  43258. _this.UV1 = false;
  43259. _this.UV2 = false;
  43260. _this.ALBEDO = false;
  43261. _this.ALBEDODIRECTUV = 0;
  43262. _this.VERTEXCOLOR = false;
  43263. _this.AMBIENT = false;
  43264. _this.AMBIENTDIRECTUV = 0;
  43265. _this.AMBIENTINGRAYSCALE = false;
  43266. _this.OPACITY = false;
  43267. _this.VERTEXALPHA = false;
  43268. _this.OPACITYDIRECTUV = 0;
  43269. _this.OPACITYRGB = false;
  43270. _this.ALPHATEST = false;
  43271. _this.DEPTHPREPASS = false;
  43272. _this.ALPHABLEND = false;
  43273. _this.ALPHAFROMALBEDO = false;
  43274. _this.ALPHATESTVALUE = "0.5";
  43275. _this.SPECULAROVERALPHA = false;
  43276. _this.RADIANCEOVERALPHA = false;
  43277. _this.ALPHAFRESNEL = false;
  43278. _this.LINEARALPHAFRESNEL = false;
  43279. _this.PREMULTIPLYALPHA = false;
  43280. _this.EMISSIVE = false;
  43281. _this.EMISSIVEDIRECTUV = 0;
  43282. _this.REFLECTIVITY = false;
  43283. _this.REFLECTIVITYDIRECTUV = 0;
  43284. _this.SPECULARTERM = false;
  43285. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43286. _this.MICROSURFACEAUTOMATIC = false;
  43287. _this.LODBASEDMICROSFURACE = false;
  43288. _this.MICROSURFACEMAP = false;
  43289. _this.MICROSURFACEMAPDIRECTUV = 0;
  43290. _this.METALLICWORKFLOW = false;
  43291. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43292. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43293. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43294. _this.AOSTOREINMETALMAPRED = false;
  43295. _this.ENVIRONMENTBRDF = false;
  43296. _this.NORMAL = false;
  43297. _this.TANGENT = false;
  43298. _this.BUMP = false;
  43299. _this.BUMPDIRECTUV = 0;
  43300. _this.OBJECTSPACE_NORMALMAP = false;
  43301. _this.PARALLAX = false;
  43302. _this.PARALLAXOCCLUSION = false;
  43303. _this.NORMALXYSCALE = true;
  43304. _this.LIGHTMAP = false;
  43305. _this.LIGHTMAPDIRECTUV = 0;
  43306. _this.USELIGHTMAPASSHADOWMAP = false;
  43307. _this.GAMMALIGHTMAP = false;
  43308. _this.REFLECTION = false;
  43309. _this.REFLECTIONMAP_3D = false;
  43310. _this.REFLECTIONMAP_SPHERICAL = false;
  43311. _this.REFLECTIONMAP_PLANAR = false;
  43312. _this.REFLECTIONMAP_CUBIC = false;
  43313. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43314. _this.REFLECTIONMAP_PROJECTION = false;
  43315. _this.REFLECTIONMAP_SKYBOX = false;
  43316. _this.REFLECTIONMAP_EXPLICIT = false;
  43317. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43318. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43319. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43320. _this.INVERTCUBICMAP = false;
  43321. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43322. _this.USESPHERICALINVERTEX = false;
  43323. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43324. _this.LODINREFLECTIONALPHA = false;
  43325. _this.GAMMAREFLECTION = false;
  43326. _this.RGBDREFLECTION = false;
  43327. _this.RADIANCEOCCLUSION = false;
  43328. _this.HORIZONOCCLUSION = false;
  43329. _this.REFRACTION = false;
  43330. _this.REFRACTIONMAP_3D = false;
  43331. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43332. _this.LODINREFRACTIONALPHA = false;
  43333. _this.GAMMAREFRACTION = false;
  43334. _this.RGBDREFRACTION = false;
  43335. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43336. _this.INSTANCES = false;
  43337. _this.NUM_BONE_INFLUENCERS = 0;
  43338. _this.BonesPerMesh = 0;
  43339. _this.NONUNIFORMSCALING = false;
  43340. _this.MORPHTARGETS = false;
  43341. _this.MORPHTARGETS_NORMAL = false;
  43342. _this.MORPHTARGETS_TANGENT = false;
  43343. _this.NUM_MORPH_INFLUENCERS = 0;
  43344. _this.IMAGEPROCESSING = false;
  43345. _this.VIGNETTE = false;
  43346. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43347. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43348. _this.TONEMAPPING = false;
  43349. _this.CONTRAST = false;
  43350. _this.COLORCURVES = false;
  43351. _this.COLORGRADING = false;
  43352. _this.COLORGRADING3D = false;
  43353. _this.SAMPLER3DGREENDEPTH = false;
  43354. _this.SAMPLER3DBGRMAP = false;
  43355. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43356. _this.EXPOSURE = false;
  43357. _this.USEPHYSICALLIGHTFALLOFF = false;
  43358. _this.TWOSIDEDLIGHTING = false;
  43359. _this.SHADOWFLOAT = false;
  43360. _this.CLIPPLANE = false;
  43361. _this.POINTSIZE = false;
  43362. _this.FOG = false;
  43363. _this.LOGARITHMICDEPTH = false;
  43364. _this.FORCENORMALFORWARD = false;
  43365. _this.SPECULARAA = false;
  43366. _this.UNLIT = false;
  43367. _this.rebuild();
  43368. return _this;
  43369. }
  43370. /**
  43371. * Resets the PBR Material defines.
  43372. */
  43373. PBRMaterialDefines.prototype.reset = function () {
  43374. _super.prototype.reset.call(this);
  43375. this.ALPHATESTVALUE = "0.5";
  43376. this.PBR = true;
  43377. };
  43378. return PBRMaterialDefines;
  43379. }(BABYLON.MaterialDefines));
  43380. /**
  43381. * The Physically based material base class of BJS.
  43382. *
  43383. * This offers the main features of a standard PBR material.
  43384. * For more information, please refer to the documentation :
  43385. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43386. */
  43387. var PBRBaseMaterial = /** @class */ (function (_super) {
  43388. __extends(PBRBaseMaterial, _super);
  43389. /**
  43390. * Instantiates a new PBRMaterial instance.
  43391. *
  43392. * @param name The material name
  43393. * @param scene The scene the material will be use in.
  43394. */
  43395. function PBRBaseMaterial(name, scene) {
  43396. var _this = _super.call(this, name, scene) || this;
  43397. /**
  43398. * Intensity of the direct lights e.g. the four lights available in your scene.
  43399. * This impacts both the direct diffuse and specular highlights.
  43400. */
  43401. _this._directIntensity = 1.0;
  43402. /**
  43403. * Intensity of the emissive part of the material.
  43404. * This helps controlling the emissive effect without modifying the emissive color.
  43405. */
  43406. _this._emissiveIntensity = 1.0;
  43407. /**
  43408. * Intensity of the environment e.g. how much the environment will light the object
  43409. * either through harmonics for rough material or through the refelction for shiny ones.
  43410. */
  43411. _this._environmentIntensity = 1.0;
  43412. /**
  43413. * This is a special control allowing the reduction of the specular highlights coming from the
  43414. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43415. */
  43416. _this._specularIntensity = 1.0;
  43417. /**
  43418. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43419. */
  43420. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43421. /**
  43422. * Debug Control allowing disabling the bump map on this material.
  43423. */
  43424. _this._disableBumpMap = false;
  43425. /**
  43426. * AKA Occlusion Texture Intensity in other nomenclature.
  43427. */
  43428. _this._ambientTextureStrength = 1.0;
  43429. /**
  43430. * The color of a material in ambient lighting.
  43431. */
  43432. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43433. /**
  43434. * AKA Diffuse Color in other nomenclature.
  43435. */
  43436. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43437. /**
  43438. * AKA Specular Color in other nomenclature.
  43439. */
  43440. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43441. /**
  43442. * The color applied when light is reflected from a material.
  43443. */
  43444. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43445. /**
  43446. * The color applied when light is emitted from a material.
  43447. */
  43448. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43449. /**
  43450. * AKA Glossiness in other nomenclature.
  43451. */
  43452. _this._microSurface = 0.9;
  43453. /**
  43454. * source material index of refraction (IOR)' / 'destination material IOR.
  43455. */
  43456. _this._indexOfRefraction = 0.66;
  43457. /**
  43458. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43459. */
  43460. _this._invertRefractionY = false;
  43461. /**
  43462. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43463. * Materials half opaque for instance using refraction could benefit from this control.
  43464. */
  43465. _this._linkRefractionWithTransparency = false;
  43466. /**
  43467. * Specifies that the material will use the light map as a show map.
  43468. */
  43469. _this._useLightmapAsShadowmap = false;
  43470. /**
  43471. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43472. * makes the reflect vector face the model (under horizon).
  43473. */
  43474. _this._useHorizonOcclusion = true;
  43475. /**
  43476. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43477. * too much the area relying on ambient texture to define their ambient occlusion.
  43478. */
  43479. _this._useRadianceOcclusion = true;
  43480. /**
  43481. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43482. */
  43483. _this._useAlphaFromAlbedoTexture = false;
  43484. /**
  43485. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43486. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43487. */
  43488. _this._useSpecularOverAlpha = true;
  43489. /**
  43490. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43491. */
  43492. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43493. /**
  43494. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43495. */
  43496. _this._useRoughnessFromMetallicTextureAlpha = true;
  43497. /**
  43498. * Specifies if the metallic texture contains the roughness information in its green channel.
  43499. */
  43500. _this._useRoughnessFromMetallicTextureGreen = false;
  43501. /**
  43502. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43503. */
  43504. _this._useMetallnessFromMetallicTextureBlue = false;
  43505. /**
  43506. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43507. */
  43508. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43509. /**
  43510. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43511. */
  43512. _this._useAmbientInGrayScale = false;
  43513. /**
  43514. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43515. * The material will try to infer what glossiness each pixel should be.
  43516. */
  43517. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43518. /**
  43519. * BJS is using an harcoded light falloff based on a manually sets up range.
  43520. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43521. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43522. */
  43523. _this._usePhysicalLightFalloff = true;
  43524. /**
  43525. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43526. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43527. */
  43528. _this._useRadianceOverAlpha = true;
  43529. /**
  43530. * Allows using an object space normal map (instead of tangent space).
  43531. */
  43532. _this._useObjectSpaceNormalMap = false;
  43533. /**
  43534. * Allows using the bump map in parallax mode.
  43535. */
  43536. _this._useParallax = false;
  43537. /**
  43538. * Allows using the bump map in parallax occlusion mode.
  43539. */
  43540. _this._useParallaxOcclusion = false;
  43541. /**
  43542. * Controls the scale bias of the parallax mode.
  43543. */
  43544. _this._parallaxScaleBias = 0.05;
  43545. /**
  43546. * If sets to true, disables all the lights affecting the material.
  43547. */
  43548. _this._disableLighting = false;
  43549. /**
  43550. * Number of Simultaneous lights allowed on the material.
  43551. */
  43552. _this._maxSimultaneousLights = 4;
  43553. /**
  43554. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43555. */
  43556. _this._invertNormalMapX = false;
  43557. /**
  43558. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43559. */
  43560. _this._invertNormalMapY = false;
  43561. /**
  43562. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43563. */
  43564. _this._twoSidedLighting = false;
  43565. /**
  43566. * Defines the alpha limits in alpha test mode.
  43567. */
  43568. _this._alphaCutOff = 0.4;
  43569. /**
  43570. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43571. */
  43572. _this._forceAlphaTest = false;
  43573. /**
  43574. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43575. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43576. */
  43577. _this._useAlphaFresnel = false;
  43578. /**
  43579. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43580. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43581. */
  43582. _this._useLinearAlphaFresnel = false;
  43583. /**
  43584. * The transparency mode of the material.
  43585. */
  43586. _this._transparencyMode = null;
  43587. /**
  43588. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43589. * from cos thetav and roughness:
  43590. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43591. */
  43592. _this._environmentBRDFTexture = null;
  43593. /**
  43594. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43595. */
  43596. _this._forceIrradianceInFragment = false;
  43597. /**
  43598. * Force normal to face away from face.
  43599. */
  43600. _this._forceNormalForward = false;
  43601. /**
  43602. * Enables specular anti aliasing in the PBR shader.
  43603. * It will both interacts on the Geometry for analytical and IBL lighting.
  43604. * It also prefilter the roughness map based on the bump values.
  43605. */
  43606. _this._enableSpecularAntiAliasing = false;
  43607. /**
  43608. * Stores the available render targets.
  43609. */
  43610. _this._renderTargets = new BABYLON.SmartArray(16);
  43611. /**
  43612. * Sets the global ambient color for the material used in lighting calculations.
  43613. */
  43614. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43615. /**
  43616. * If set to true, no lighting calculations will be applied.
  43617. */
  43618. _this._unlit = false;
  43619. // Setup the default processing configuration to the scene.
  43620. _this._attachImageProcessingConfiguration(null);
  43621. _this.getRenderTargetTextures = function () {
  43622. _this._renderTargets.reset();
  43623. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43624. _this._renderTargets.push(_this._reflectionTexture);
  43625. }
  43626. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43627. _this._renderTargets.push(_this._refractionTexture);
  43628. }
  43629. return _this._renderTargets;
  43630. };
  43631. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43632. return _this;
  43633. }
  43634. /**
  43635. * Attaches a new image processing configuration to the PBR Material.
  43636. * @param configuration
  43637. */
  43638. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43639. var _this = this;
  43640. if (configuration === this._imageProcessingConfiguration) {
  43641. return;
  43642. }
  43643. // Detaches observer.
  43644. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43645. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43646. }
  43647. // Pick the scene configuration if needed.
  43648. if (!configuration) {
  43649. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43650. }
  43651. else {
  43652. this._imageProcessingConfiguration = configuration;
  43653. }
  43654. // Attaches observer.
  43655. if (this._imageProcessingConfiguration) {
  43656. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43657. _this._markAllSubMeshesAsImageProcessingDirty();
  43658. });
  43659. }
  43660. };
  43661. /**
  43662. * Gets the name of the material class.
  43663. */
  43664. PBRBaseMaterial.prototype.getClassName = function () {
  43665. return "PBRBaseMaterial";
  43666. };
  43667. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43668. /**
  43669. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43670. */
  43671. get: function () {
  43672. return this._useLogarithmicDepth;
  43673. },
  43674. /**
  43675. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43676. */
  43677. set: function (value) {
  43678. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43679. },
  43680. enumerable: true,
  43681. configurable: true
  43682. });
  43683. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43684. /**
  43685. * Gets the current transparency mode.
  43686. */
  43687. get: function () {
  43688. return this._transparencyMode;
  43689. },
  43690. /**
  43691. * Sets the transparency mode of the material.
  43692. *
  43693. * | Value | Type | Description |
  43694. * | ----- | ----------------------------------- | ----------- |
  43695. * | 0 | OPAQUE | |
  43696. * | 1 | ALPHATEST | |
  43697. * | 2 | ALPHABLEND | |
  43698. * | 3 | ALPHATESTANDBLEND | |
  43699. *
  43700. */
  43701. set: function (value) {
  43702. if (this._transparencyMode === value) {
  43703. return;
  43704. }
  43705. this._transparencyMode = value;
  43706. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43707. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43708. },
  43709. enumerable: true,
  43710. configurable: true
  43711. });
  43712. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43713. /**
  43714. * Returns true if alpha blending should be disabled.
  43715. */
  43716. get: function () {
  43717. return (this._linkRefractionWithTransparency ||
  43718. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43719. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43720. },
  43721. enumerable: true,
  43722. configurable: true
  43723. });
  43724. /**
  43725. * Specifies whether or not this material should be rendered in alpha blend mode.
  43726. */
  43727. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43728. if (this._disableAlphaBlending) {
  43729. return false;
  43730. }
  43731. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43732. };
  43733. /**
  43734. * Specifies if the mesh will require alpha blending.
  43735. * @param mesh - BJS mesh.
  43736. */
  43737. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43738. if (this._disableAlphaBlending) {
  43739. return false;
  43740. }
  43741. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43742. };
  43743. /**
  43744. * Specifies whether or not this material should be rendered in alpha test mode.
  43745. */
  43746. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43747. if (this._forceAlphaTest) {
  43748. return true;
  43749. }
  43750. if (this._linkRefractionWithTransparency) {
  43751. return false;
  43752. }
  43753. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43754. };
  43755. /**
  43756. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43757. */
  43758. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43759. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43760. };
  43761. /**
  43762. * Gets the texture used for the alpha test.
  43763. */
  43764. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43765. return this._albedoTexture;
  43766. };
  43767. /**
  43768. * Specifies that the submesh is ready to be used.
  43769. * @param mesh - BJS mesh.
  43770. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43771. * @param useInstances - Specifies that instances should be used.
  43772. * @returns - boolean indicating that the submesh is ready or not.
  43773. */
  43774. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43775. if (subMesh.effect && this.isFrozen) {
  43776. if (this._wasPreviouslyReady) {
  43777. return true;
  43778. }
  43779. }
  43780. if (!subMesh._materialDefines) {
  43781. subMesh._materialDefines = new PBRMaterialDefines();
  43782. }
  43783. var defines = subMesh._materialDefines;
  43784. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43785. if (defines._renderId === this.getScene().getRenderId()) {
  43786. return true;
  43787. }
  43788. }
  43789. var scene = this.getScene();
  43790. var engine = scene.getEngine();
  43791. if (defines._areTexturesDirty) {
  43792. if (scene.texturesEnabled) {
  43793. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43794. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43795. return false;
  43796. }
  43797. }
  43798. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43799. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43800. return false;
  43801. }
  43802. }
  43803. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43804. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43805. return false;
  43806. }
  43807. }
  43808. var reflectionTexture = this._getReflectionTexture();
  43809. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43810. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43811. return false;
  43812. }
  43813. }
  43814. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43815. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43816. return false;
  43817. }
  43818. }
  43819. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43820. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43821. return false;
  43822. }
  43823. }
  43824. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43825. if (this._metallicTexture) {
  43826. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43827. return false;
  43828. }
  43829. }
  43830. else if (this._reflectivityTexture) {
  43831. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43832. return false;
  43833. }
  43834. }
  43835. if (this._microSurfaceTexture) {
  43836. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43837. return false;
  43838. }
  43839. }
  43840. }
  43841. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43842. // Bump texture cannot be not blocking.
  43843. if (!this._bumpTexture.isReady()) {
  43844. return false;
  43845. }
  43846. }
  43847. var refractionTexture = this._getRefractionTexture();
  43848. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43849. if (!refractionTexture.isReadyOrNotBlocking()) {
  43850. return false;
  43851. }
  43852. }
  43853. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43854. // This is blocking.
  43855. if (!this._environmentBRDFTexture.isReady()) {
  43856. return false;
  43857. }
  43858. }
  43859. }
  43860. }
  43861. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43862. if (!this._imageProcessingConfiguration.isReady()) {
  43863. return false;
  43864. }
  43865. }
  43866. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43867. mesh.createNormals(true);
  43868. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43869. }
  43870. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43871. if (effect) {
  43872. scene.resetCachedMaterial();
  43873. subMesh.setEffect(effect, defines);
  43874. this.buildUniformLayout();
  43875. }
  43876. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43877. return false;
  43878. }
  43879. defines._renderId = scene.getRenderId();
  43880. this._wasPreviouslyReady = true;
  43881. return true;
  43882. };
  43883. /**
  43884. * Specifies if the material uses metallic roughness workflow.
  43885. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43886. */
  43887. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43888. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43889. return true;
  43890. }
  43891. return false;
  43892. };
  43893. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43894. if (onCompiled === void 0) { onCompiled = null; }
  43895. if (onError === void 0) { onError = null; }
  43896. if (useInstances === void 0) { useInstances = null; }
  43897. if (useClipPlane === void 0) { useClipPlane = null; }
  43898. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43899. if (!defines.isDirty) {
  43900. return null;
  43901. }
  43902. defines.markAsProcessed();
  43903. var scene = this.getScene();
  43904. var engine = scene.getEngine();
  43905. // Fallbacks
  43906. var fallbacks = new BABYLON.EffectFallbacks();
  43907. var fallbackRank = 0;
  43908. if (defines.USESPHERICALINVERTEX) {
  43909. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43910. }
  43911. if (defines.FOG) {
  43912. fallbacks.addFallback(fallbackRank, "FOG");
  43913. }
  43914. if (defines.SPECULARAA) {
  43915. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43916. }
  43917. if (defines.POINTSIZE) {
  43918. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43919. }
  43920. if (defines.LOGARITHMICDEPTH) {
  43921. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43922. }
  43923. if (defines.PARALLAX) {
  43924. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43925. }
  43926. if (defines.PARALLAXOCCLUSION) {
  43927. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43928. }
  43929. if (defines.ENVIRONMENTBRDF) {
  43930. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43931. }
  43932. if (defines.TANGENT) {
  43933. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43934. }
  43935. if (defines.BUMP) {
  43936. fallbacks.addFallback(fallbackRank++, "BUMP");
  43937. }
  43938. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43939. if (defines.SPECULARTERM) {
  43940. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43941. }
  43942. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43943. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43944. }
  43945. if (defines.LIGHTMAP) {
  43946. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43947. }
  43948. if (defines.NORMAL) {
  43949. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43950. }
  43951. if (defines.AMBIENT) {
  43952. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43953. }
  43954. if (defines.EMISSIVE) {
  43955. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43956. }
  43957. if (defines.VERTEXCOLOR) {
  43958. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  43959. }
  43960. if (defines.NUM_BONE_INFLUENCERS > 0) {
  43961. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  43962. }
  43963. if (defines.MORPHTARGETS) {
  43964. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  43965. }
  43966. //Attributes
  43967. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43968. if (defines.NORMAL) {
  43969. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43970. }
  43971. if (defines.TANGENT) {
  43972. attribs.push(BABYLON.VertexBuffer.TangentKind);
  43973. }
  43974. if (defines.UV1) {
  43975. attribs.push(BABYLON.VertexBuffer.UVKind);
  43976. }
  43977. if (defines.UV2) {
  43978. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43979. }
  43980. if (defines.VERTEXCOLOR) {
  43981. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43982. }
  43983. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43984. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43985. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43986. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  43987. "vFogInfos", "vFogColor", "pointSize",
  43988. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  43989. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43990. "mBones",
  43991. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  43992. "vLightingIntensity",
  43993. "logarithmicDepthConstant",
  43994. "vSphericalX", "vSphericalY", "vSphericalZ",
  43995. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  43996. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  43997. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  43998. "vTangentSpaceParams"
  43999. ];
  44000. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44001. "bumpSampler", "lightmapSampler", "opacitySampler",
  44002. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44003. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44004. "microSurfaceSampler", "environmentBrdfSampler"];
  44005. var uniformBuffers = ["Material", "Scene"];
  44006. if (BABYLON.ImageProcessingConfiguration) {
  44007. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44008. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44009. }
  44010. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44011. uniformsNames: uniforms,
  44012. uniformBuffersNames: uniformBuffers,
  44013. samplers: samplers,
  44014. defines: defines,
  44015. maxSimultaneousLights: this._maxSimultaneousLights
  44016. });
  44017. var join = defines.toString();
  44018. return engine.createEffect("pbr", {
  44019. attributes: attribs,
  44020. uniformsNames: uniforms,
  44021. uniformBuffersNames: uniformBuffers,
  44022. samplers: samplers,
  44023. defines: join,
  44024. fallbacks: fallbacks,
  44025. onCompiled: onCompiled,
  44026. onError: onError,
  44027. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44028. }, engine);
  44029. };
  44030. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44031. if (useInstances === void 0) { useInstances = null; }
  44032. if (useClipPlane === void 0) { useClipPlane = null; }
  44033. var scene = this.getScene();
  44034. var engine = scene.getEngine();
  44035. // Lights
  44036. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44037. defines._needNormals = true;
  44038. // Textures
  44039. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44040. if (defines._areTexturesDirty) {
  44041. defines._needUVs = false;
  44042. if (scene.texturesEnabled) {
  44043. if (scene.getEngine().getCaps().textureLOD) {
  44044. defines.LODBASEDMICROSFURACE = true;
  44045. }
  44046. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44047. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44048. }
  44049. else {
  44050. defines.ALBEDO = false;
  44051. }
  44052. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44053. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44054. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44055. }
  44056. else {
  44057. defines.AMBIENT = false;
  44058. }
  44059. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44060. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44061. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44062. }
  44063. else {
  44064. defines.OPACITY = false;
  44065. }
  44066. var reflectionTexture = this._getReflectionTexture();
  44067. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44068. defines.REFLECTION = true;
  44069. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44070. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44071. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44072. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44073. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44074. defines.INVERTCUBICMAP = true;
  44075. }
  44076. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44077. switch (reflectionTexture.coordinatesMode) {
  44078. case BABYLON.Texture.EXPLICIT_MODE:
  44079. defines.REFLECTIONMAP_EXPLICIT = true;
  44080. break;
  44081. case BABYLON.Texture.PLANAR_MODE:
  44082. defines.REFLECTIONMAP_PLANAR = true;
  44083. break;
  44084. case BABYLON.Texture.PROJECTION_MODE:
  44085. defines.REFLECTIONMAP_PROJECTION = true;
  44086. break;
  44087. case BABYLON.Texture.SKYBOX_MODE:
  44088. defines.REFLECTIONMAP_SKYBOX = true;
  44089. break;
  44090. case BABYLON.Texture.SPHERICAL_MODE:
  44091. defines.REFLECTIONMAP_SPHERICAL = true;
  44092. break;
  44093. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44094. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44095. break;
  44096. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44097. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44098. break;
  44099. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44100. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44101. break;
  44102. case BABYLON.Texture.CUBIC_MODE:
  44103. case BABYLON.Texture.INVCUBIC_MODE:
  44104. default:
  44105. defines.REFLECTIONMAP_CUBIC = true;
  44106. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44107. break;
  44108. }
  44109. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44110. if (reflectionTexture.sphericalPolynomial) {
  44111. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44112. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44113. defines.USESPHERICALINVERTEX = false;
  44114. }
  44115. else {
  44116. defines.USESPHERICALINVERTEX = true;
  44117. }
  44118. }
  44119. }
  44120. }
  44121. else {
  44122. defines.REFLECTION = false;
  44123. defines.REFLECTIONMAP_3D = false;
  44124. defines.REFLECTIONMAP_SPHERICAL = false;
  44125. defines.REFLECTIONMAP_PLANAR = false;
  44126. defines.REFLECTIONMAP_CUBIC = false;
  44127. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44128. defines.REFLECTIONMAP_PROJECTION = false;
  44129. defines.REFLECTIONMAP_SKYBOX = false;
  44130. defines.REFLECTIONMAP_EXPLICIT = false;
  44131. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44132. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44133. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44134. defines.INVERTCUBICMAP = false;
  44135. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44136. defines.USESPHERICALINVERTEX = false;
  44137. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44138. defines.LODINREFLECTIONALPHA = false;
  44139. defines.GAMMAREFLECTION = false;
  44140. defines.RGBDREFLECTION = false;
  44141. }
  44142. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44143. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44144. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44145. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44146. }
  44147. else {
  44148. defines.LIGHTMAP = false;
  44149. }
  44150. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44151. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44152. }
  44153. else {
  44154. defines.EMISSIVE = false;
  44155. }
  44156. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44157. if (this._metallicTexture) {
  44158. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44159. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44160. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44161. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44162. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44163. }
  44164. else if (this._reflectivityTexture) {
  44165. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44166. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44167. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44168. }
  44169. else {
  44170. defines.REFLECTIVITY = false;
  44171. }
  44172. if (this._microSurfaceTexture) {
  44173. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44174. }
  44175. else {
  44176. defines.MICROSURFACEMAP = false;
  44177. }
  44178. }
  44179. else {
  44180. defines.REFLECTIVITY = false;
  44181. defines.MICROSURFACEMAP = false;
  44182. }
  44183. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44184. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44185. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44186. defines.PARALLAX = true;
  44187. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44188. }
  44189. else {
  44190. defines.PARALLAX = false;
  44191. }
  44192. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44193. }
  44194. else {
  44195. defines.BUMP = false;
  44196. }
  44197. var refractionTexture = this._getRefractionTexture();
  44198. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44199. defines.REFRACTION = true;
  44200. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44201. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44202. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44203. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44204. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44205. if (this._linkRefractionWithTransparency) {
  44206. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44207. }
  44208. }
  44209. else {
  44210. defines.REFRACTION = false;
  44211. }
  44212. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44213. defines.ENVIRONMENTBRDF = true;
  44214. }
  44215. else {
  44216. defines.ENVIRONMENTBRDF = false;
  44217. }
  44218. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44219. defines.ALPHAFROMALBEDO = true;
  44220. }
  44221. else {
  44222. defines.ALPHAFROMALBEDO = false;
  44223. }
  44224. }
  44225. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44226. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44227. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44228. if (!this.backFaceCulling && this._twoSidedLighting) {
  44229. defines.TWOSIDEDLIGHTING = true;
  44230. }
  44231. else {
  44232. defines.TWOSIDEDLIGHTING = false;
  44233. }
  44234. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44235. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44236. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44237. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44238. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44239. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44240. }
  44241. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44242. this._imageProcessingConfiguration.prepareDefines(defines);
  44243. }
  44244. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44245. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44246. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44247. // Misc.
  44248. if (defines._areMiscDirty) {
  44249. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44250. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44251. }
  44252. // Values that need to be evaluated on every frame
  44253. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44254. // Attribs
  44255. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44256. };
  44257. /**
  44258. * Force shader compilation
  44259. */
  44260. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44261. var _this = this;
  44262. var localOptions = __assign({ clipPlane: false }, options);
  44263. var defines = new PBRMaterialDefines();
  44264. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44265. if (effect.isReady()) {
  44266. if (onCompiled) {
  44267. onCompiled(this);
  44268. }
  44269. }
  44270. else {
  44271. effect.onCompileObservable.add(function () {
  44272. if (onCompiled) {
  44273. onCompiled(_this);
  44274. }
  44275. });
  44276. }
  44277. };
  44278. /**
  44279. * Initializes the uniform buffer layout for the shader.
  44280. */
  44281. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44282. // Order is important !
  44283. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44284. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44285. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44286. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44287. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44288. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44289. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44290. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44291. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44292. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44293. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44294. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44295. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44296. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44297. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44298. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44299. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44300. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44301. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44302. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44303. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44304. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44305. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44306. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44307. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44308. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44309. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44310. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44311. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44312. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44313. this._uniformBuffer.addUniform("pointSize", 1);
  44314. this._uniformBuffer.create();
  44315. };
  44316. /**
  44317. * Unbinds the textures.
  44318. */
  44319. PBRBaseMaterial.prototype.unbind = function () {
  44320. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44321. this._uniformBuffer.setTexture("reflectionSampler", null);
  44322. }
  44323. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44324. this._uniformBuffer.setTexture("refractionSampler", null);
  44325. }
  44326. _super.prototype.unbind.call(this);
  44327. };
  44328. /**
  44329. * Binds the submesh data.
  44330. * @param world - The world matrix.
  44331. * @param mesh - The BJS mesh.
  44332. * @param subMesh - A submesh of the BJS mesh.
  44333. */
  44334. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44335. var scene = this.getScene();
  44336. var defines = subMesh._materialDefines;
  44337. if (!defines) {
  44338. return;
  44339. }
  44340. var effect = subMesh.effect;
  44341. if (!effect) {
  44342. return;
  44343. }
  44344. this._activeEffect = effect;
  44345. // Matrices
  44346. this.bindOnlyWorldMatrix(world);
  44347. // Normal Matrix
  44348. if (defines.OBJECTSPACE_NORMALMAP) {
  44349. world.toNormalMatrix(this._normalMatrix);
  44350. this.bindOnlyNormalMatrix(this._normalMatrix);
  44351. }
  44352. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44353. // Bones
  44354. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44355. var reflectionTexture = null;
  44356. if (mustRebind) {
  44357. this._uniformBuffer.bindToEffect(effect, "Material");
  44358. this.bindViewProjection(effect);
  44359. reflectionTexture = this._getReflectionTexture();
  44360. var refractionTexture = this._getRefractionTexture();
  44361. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44362. // Texture uniforms
  44363. if (scene.texturesEnabled) {
  44364. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44365. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44366. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44367. }
  44368. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44369. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44370. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44371. }
  44372. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44373. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44374. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44375. }
  44376. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44377. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44378. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44379. if (reflectionTexture.boundingBoxSize) {
  44380. var cubeTexture = reflectionTexture;
  44381. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44382. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44383. }
  44384. var polynomials = reflectionTexture.sphericalPolynomial;
  44385. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44386. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44387. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44388. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44389. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44390. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44391. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44392. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44393. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44394. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44395. }
  44396. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44397. }
  44398. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44399. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44400. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44401. }
  44402. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44403. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44404. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44405. }
  44406. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44407. if (this._metallicTexture) {
  44408. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44409. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44410. }
  44411. else if (this._reflectivityTexture) {
  44412. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44413. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44414. }
  44415. if (this._microSurfaceTexture) {
  44416. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44417. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44418. }
  44419. }
  44420. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44421. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44422. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44423. if (scene._mirroredCameraPosition) {
  44424. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44425. }
  44426. else {
  44427. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44428. }
  44429. }
  44430. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44431. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44432. var depth = 1.0;
  44433. if (!refractionTexture.isCube) {
  44434. if (refractionTexture.depth) {
  44435. depth = refractionTexture.depth;
  44436. }
  44437. }
  44438. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44439. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44440. }
  44441. }
  44442. // Point size
  44443. if (this.pointsCloud) {
  44444. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44445. }
  44446. // Colors
  44447. if (defines.METALLICWORKFLOW) {
  44448. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44449. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44450. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44451. }
  44452. else {
  44453. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44454. }
  44455. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44456. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44457. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44458. // Misc
  44459. this._lightingInfos.x = this._directIntensity;
  44460. this._lightingInfos.y = this._emissiveIntensity;
  44461. this._lightingInfos.z = this._environmentIntensity;
  44462. this._lightingInfos.w = this._specularIntensity;
  44463. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44464. }
  44465. // Textures
  44466. if (scene.texturesEnabled) {
  44467. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44468. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44469. }
  44470. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44471. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44472. }
  44473. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44474. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44475. }
  44476. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44477. if (defines.LODBASEDMICROSFURACE) {
  44478. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44479. }
  44480. else {
  44481. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44482. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44483. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44484. }
  44485. }
  44486. if (defines.ENVIRONMENTBRDF) {
  44487. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44488. }
  44489. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44490. if (defines.LODBASEDMICROSFURACE) {
  44491. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44492. }
  44493. else {
  44494. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44495. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44496. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44497. }
  44498. }
  44499. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44500. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44501. }
  44502. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44503. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44504. }
  44505. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44506. if (this._metallicTexture) {
  44507. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44508. }
  44509. else if (this._reflectivityTexture) {
  44510. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44511. }
  44512. if (this._microSurfaceTexture) {
  44513. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44514. }
  44515. }
  44516. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44517. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44518. }
  44519. }
  44520. // Clip plane
  44521. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44522. // Colors
  44523. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44524. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44525. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44526. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44527. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44528. }
  44529. if (mustRebind || !this.isFrozen) {
  44530. // Lights
  44531. if (scene.lightsEnabled && !this._disableLighting) {
  44532. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44533. }
  44534. // View
  44535. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44536. this.bindView(effect);
  44537. }
  44538. // Fog
  44539. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44540. // Morph targets
  44541. if (defines.NUM_MORPH_INFLUENCERS) {
  44542. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44543. }
  44544. // image processing
  44545. this._imageProcessingConfiguration.bind(this._activeEffect);
  44546. // Log. depth
  44547. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44548. }
  44549. this._uniformBuffer.update();
  44550. this._afterBind(mesh, this._activeEffect);
  44551. };
  44552. /**
  44553. * Returns the animatable textures.
  44554. * @returns - Array of animatable textures.
  44555. */
  44556. PBRBaseMaterial.prototype.getAnimatables = function () {
  44557. var results = [];
  44558. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44559. results.push(this._albedoTexture);
  44560. }
  44561. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44562. results.push(this._ambientTexture);
  44563. }
  44564. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44565. results.push(this._opacityTexture);
  44566. }
  44567. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44568. results.push(this._reflectionTexture);
  44569. }
  44570. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44571. results.push(this._emissiveTexture);
  44572. }
  44573. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44574. results.push(this._metallicTexture);
  44575. }
  44576. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44577. results.push(this._reflectivityTexture);
  44578. }
  44579. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44580. results.push(this._bumpTexture);
  44581. }
  44582. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44583. results.push(this._lightmapTexture);
  44584. }
  44585. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44586. results.push(this._refractionTexture);
  44587. }
  44588. return results;
  44589. };
  44590. /**
  44591. * Returns the texture used for reflections.
  44592. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44593. */
  44594. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44595. if (this._reflectionTexture) {
  44596. return this._reflectionTexture;
  44597. }
  44598. return this.getScene().environmentTexture;
  44599. };
  44600. /**
  44601. * Returns the texture used for refraction or null if none is used.
  44602. * @returns - Refection texture if present. If no refraction texture and refraction
  44603. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44604. */
  44605. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44606. if (this._refractionTexture) {
  44607. return this._refractionTexture;
  44608. }
  44609. if (this._linkRefractionWithTransparency) {
  44610. return this.getScene().environmentTexture;
  44611. }
  44612. return null;
  44613. };
  44614. /**
  44615. * Disposes the resources of the material.
  44616. * @param forceDisposeEffect - Forces the disposal of effects.
  44617. * @param forceDisposeTextures - Forces the disposal of all textures.
  44618. */
  44619. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44620. if (forceDisposeTextures) {
  44621. if (this._albedoTexture) {
  44622. this._albedoTexture.dispose();
  44623. }
  44624. if (this._ambientTexture) {
  44625. this._ambientTexture.dispose();
  44626. }
  44627. if (this._opacityTexture) {
  44628. this._opacityTexture.dispose();
  44629. }
  44630. if (this._reflectionTexture) {
  44631. this._reflectionTexture.dispose();
  44632. }
  44633. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44634. this._environmentBRDFTexture.dispose();
  44635. }
  44636. if (this._emissiveTexture) {
  44637. this._emissiveTexture.dispose();
  44638. }
  44639. if (this._metallicTexture) {
  44640. this._metallicTexture.dispose();
  44641. }
  44642. if (this._reflectivityTexture) {
  44643. this._reflectivityTexture.dispose();
  44644. }
  44645. if (this._bumpTexture) {
  44646. this._bumpTexture.dispose();
  44647. }
  44648. if (this._lightmapTexture) {
  44649. this._lightmapTexture.dispose();
  44650. }
  44651. if (this._refractionTexture) {
  44652. this._refractionTexture.dispose();
  44653. }
  44654. }
  44655. this._renderTargets.dispose();
  44656. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44657. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44658. }
  44659. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44660. };
  44661. /**
  44662. * Stores the reflectivity values based on metallic roughness workflow.
  44663. */
  44664. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44665. __decorate([
  44666. BABYLON.serializeAsImageProcessingConfiguration()
  44667. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44668. __decorate([
  44669. BABYLON.serialize()
  44670. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44671. __decorate([
  44672. BABYLON.serialize()
  44673. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44674. return PBRBaseMaterial;
  44675. }(BABYLON.PushMaterial));
  44676. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44677. })(BABYLON || (BABYLON = {}));
  44678. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44679. var BABYLON;
  44680. (function (BABYLON) {
  44681. /**
  44682. * The Physically based simple base material of BJS.
  44683. *
  44684. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44685. * It is used as the base class for both the specGloss and metalRough conventions.
  44686. */
  44687. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44688. __extends(PBRBaseSimpleMaterial, _super);
  44689. /**
  44690. * Instantiates a new PBRMaterial instance.
  44691. *
  44692. * @param name The material name
  44693. * @param scene The scene the material will be use in.
  44694. */
  44695. function PBRBaseSimpleMaterial(name, scene) {
  44696. var _this = _super.call(this, name, scene) || this;
  44697. /**
  44698. * Number of Simultaneous lights allowed on the material.
  44699. */
  44700. _this.maxSimultaneousLights = 4;
  44701. /**
  44702. * If sets to true, disables all the lights affecting the material.
  44703. */
  44704. _this.disableLighting = false;
  44705. /**
  44706. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44707. */
  44708. _this.invertNormalMapX = false;
  44709. /**
  44710. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44711. */
  44712. _this.invertNormalMapY = false;
  44713. /**
  44714. * Emissivie color used to self-illuminate the model.
  44715. */
  44716. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44717. /**
  44718. * Occlusion Channel Strenght.
  44719. */
  44720. _this.occlusionStrength = 1.0;
  44721. _this.useLightmapAsShadowmap = false;
  44722. _this._useAlphaFromAlbedoTexture = true;
  44723. _this._useAmbientInGrayScale = true;
  44724. return _this;
  44725. }
  44726. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44727. /**
  44728. * Gets the current double sided mode.
  44729. */
  44730. get: function () {
  44731. return this._twoSidedLighting;
  44732. },
  44733. /**
  44734. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44735. */
  44736. set: function (value) {
  44737. if (this._twoSidedLighting === value) {
  44738. return;
  44739. }
  44740. this._twoSidedLighting = value;
  44741. this.backFaceCulling = !value;
  44742. this._markAllSubMeshesAsTexturesDirty();
  44743. },
  44744. enumerable: true,
  44745. configurable: true
  44746. });
  44747. /**
  44748. * Return the active textures of the material.
  44749. */
  44750. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44751. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44752. if (this.environmentTexture) {
  44753. activeTextures.push(this.environmentTexture);
  44754. }
  44755. if (this.normalTexture) {
  44756. activeTextures.push(this.normalTexture);
  44757. }
  44758. if (this.emissiveTexture) {
  44759. activeTextures.push(this.emissiveTexture);
  44760. }
  44761. if (this.occlusionTexture) {
  44762. activeTextures.push(this.occlusionTexture);
  44763. }
  44764. if (this.lightmapTexture) {
  44765. activeTextures.push(this.lightmapTexture);
  44766. }
  44767. return activeTextures;
  44768. };
  44769. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44770. if (_super.prototype.hasTexture.call(this, texture)) {
  44771. return true;
  44772. }
  44773. if (this.lightmapTexture === texture) {
  44774. return true;
  44775. }
  44776. return false;
  44777. };
  44778. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44779. return "PBRBaseSimpleMaterial";
  44780. };
  44781. __decorate([
  44782. BABYLON.serialize(),
  44783. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44784. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44785. __decorate([
  44786. BABYLON.serialize(),
  44787. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44788. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44789. __decorate([
  44790. BABYLON.serializeAsTexture(),
  44791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44792. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44793. __decorate([
  44794. BABYLON.serialize(),
  44795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44796. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44797. __decorate([
  44798. BABYLON.serialize(),
  44799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44800. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44801. __decorate([
  44802. BABYLON.serializeAsTexture(),
  44803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44804. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44805. __decorate([
  44806. BABYLON.serializeAsColor3("emissive"),
  44807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44808. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44809. __decorate([
  44810. BABYLON.serializeAsTexture(),
  44811. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44812. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44813. __decorate([
  44814. BABYLON.serialize(),
  44815. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44816. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44817. __decorate([
  44818. BABYLON.serializeAsTexture(),
  44819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44820. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44821. __decorate([
  44822. BABYLON.serialize(),
  44823. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44824. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44825. __decorate([
  44826. BABYLON.serialize()
  44827. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44828. __decorate([
  44829. BABYLON.serializeAsTexture(),
  44830. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44831. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44832. __decorate([
  44833. BABYLON.serialize(),
  44834. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44835. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44836. return PBRBaseSimpleMaterial;
  44837. }(BABYLON.PBRBaseMaterial));
  44838. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44839. })(BABYLON || (BABYLON = {}));
  44840. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44841. var BABYLON;
  44842. (function (BABYLON) {
  44843. /**
  44844. * The Physically based material of BJS.
  44845. *
  44846. * This offers the main features of a standard PBR material.
  44847. * For more information, please refer to the documentation :
  44848. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44849. */
  44850. var PBRMaterial = /** @class */ (function (_super) {
  44851. __extends(PBRMaterial, _super);
  44852. /**
  44853. * Instantiates a new PBRMaterial instance.
  44854. *
  44855. * @param name The material name
  44856. * @param scene The scene the material will be use in.
  44857. */
  44858. function PBRMaterial(name, scene) {
  44859. var _this = _super.call(this, name, scene) || this;
  44860. /**
  44861. * Intensity of the direct lights e.g. the four lights available in your scene.
  44862. * This impacts both the direct diffuse and specular highlights.
  44863. */
  44864. _this.directIntensity = 1.0;
  44865. /**
  44866. * Intensity of the emissive part of the material.
  44867. * This helps controlling the emissive effect without modifying the emissive color.
  44868. */
  44869. _this.emissiveIntensity = 1.0;
  44870. /**
  44871. * Intensity of the environment e.g. how much the environment will light the object
  44872. * either through harmonics for rough material or through the refelction for shiny ones.
  44873. */
  44874. _this.environmentIntensity = 1.0;
  44875. /**
  44876. * This is a special control allowing the reduction of the specular highlights coming from the
  44877. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44878. */
  44879. _this.specularIntensity = 1.0;
  44880. /**
  44881. * Debug Control allowing disabling the bump map on this material.
  44882. */
  44883. _this.disableBumpMap = false;
  44884. /**
  44885. * AKA Occlusion Texture Intensity in other nomenclature.
  44886. */
  44887. _this.ambientTextureStrength = 1.0;
  44888. /**
  44889. * The color of a material in ambient lighting.
  44890. */
  44891. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44892. /**
  44893. * AKA Diffuse Color in other nomenclature.
  44894. */
  44895. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44896. /**
  44897. * AKA Specular Color in other nomenclature.
  44898. */
  44899. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44900. /**
  44901. * The color reflected from the material.
  44902. */
  44903. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44904. /**
  44905. * The color emitted from the material.
  44906. */
  44907. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44908. /**
  44909. * AKA Glossiness in other nomenclature.
  44910. */
  44911. _this.microSurface = 1.0;
  44912. /**
  44913. * source material index of refraction (IOR)' / 'destination material IOR.
  44914. */
  44915. _this.indexOfRefraction = 0.66;
  44916. /**
  44917. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44918. */
  44919. _this.invertRefractionY = false;
  44920. /**
  44921. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44922. * Materials half opaque for instance using refraction could benefit from this control.
  44923. */
  44924. _this.linkRefractionWithTransparency = false;
  44925. _this.useLightmapAsShadowmap = false;
  44926. /**
  44927. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44928. */
  44929. _this.useAlphaFromAlbedoTexture = false;
  44930. /**
  44931. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44932. */
  44933. _this.forceAlphaTest = false;
  44934. /**
  44935. * Defines the alpha limits in alpha test mode.
  44936. */
  44937. _this.alphaCutOff = 0.4;
  44938. /**
  44939. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44940. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44941. */
  44942. _this.useSpecularOverAlpha = true;
  44943. /**
  44944. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44945. */
  44946. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44947. /**
  44948. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44949. */
  44950. _this.useRoughnessFromMetallicTextureAlpha = true;
  44951. /**
  44952. * Specifies if the metallic texture contains the roughness information in its green channel.
  44953. */
  44954. _this.useRoughnessFromMetallicTextureGreen = false;
  44955. /**
  44956. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44957. */
  44958. _this.useMetallnessFromMetallicTextureBlue = false;
  44959. /**
  44960. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44961. */
  44962. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  44963. /**
  44964. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44965. */
  44966. _this.useAmbientInGrayScale = false;
  44967. /**
  44968. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44969. * The material will try to infer what glossiness each pixel should be.
  44970. */
  44971. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  44972. /**
  44973. * BJS is using an harcoded light falloff based on a manually sets up range.
  44974. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44975. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44976. */
  44977. _this.usePhysicalLightFalloff = true;
  44978. /**
  44979. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44980. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44981. */
  44982. _this.useRadianceOverAlpha = true;
  44983. /**
  44984. * Allows using an object space normal map (instead of tangent space).
  44985. */
  44986. _this.useObjectSpaceNormalMap = false;
  44987. /**
  44988. * Allows using the bump map in parallax mode.
  44989. */
  44990. _this.useParallax = false;
  44991. /**
  44992. * Allows using the bump map in parallax occlusion mode.
  44993. */
  44994. _this.useParallaxOcclusion = false;
  44995. /**
  44996. * Controls the scale bias of the parallax mode.
  44997. */
  44998. _this.parallaxScaleBias = 0.05;
  44999. /**
  45000. * If sets to true, disables all the lights affecting the material.
  45001. */
  45002. _this.disableLighting = false;
  45003. /**
  45004. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45005. */
  45006. _this.forceIrradianceInFragment = false;
  45007. /**
  45008. * Number of Simultaneous lights allowed on the material.
  45009. */
  45010. _this.maxSimultaneousLights = 4;
  45011. /**
  45012. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45013. */
  45014. _this.invertNormalMapX = false;
  45015. /**
  45016. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45017. */
  45018. _this.invertNormalMapY = false;
  45019. /**
  45020. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45021. */
  45022. _this.twoSidedLighting = false;
  45023. /**
  45024. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45025. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45026. */
  45027. _this.useAlphaFresnel = false;
  45028. /**
  45029. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45030. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45031. */
  45032. _this.useLinearAlphaFresnel = false;
  45033. /**
  45034. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45035. * And/Or occlude the blended part.
  45036. */
  45037. _this.environmentBRDFTexture = null;
  45038. /**
  45039. * Force normal to face away from face.
  45040. */
  45041. _this.forceNormalForward = false;
  45042. /**
  45043. * Enables specular anti aliasing in the PBR shader.
  45044. * It will both interacts on the Geometry for analytical and IBL lighting.
  45045. * It also prefilter the roughness map based on the bump values.
  45046. */
  45047. _this.enableSpecularAntiAliasing = false;
  45048. /**
  45049. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45050. * makes the reflect vector face the model (under horizon).
  45051. */
  45052. _this.useHorizonOcclusion = true;
  45053. /**
  45054. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45055. * too much the area relying on ambient texture to define their ambient occlusion.
  45056. */
  45057. _this.useRadianceOcclusion = true;
  45058. /**
  45059. * If set to true, no lighting calculations will be applied.
  45060. */
  45061. _this.unlit = false;
  45062. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45063. return _this;
  45064. }
  45065. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45066. /**
  45067. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45068. */
  45069. get: function () {
  45070. return this._PBRMATERIAL_OPAQUE;
  45071. },
  45072. enumerable: true,
  45073. configurable: true
  45074. });
  45075. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45076. /**
  45077. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45078. */
  45079. get: function () {
  45080. return this._PBRMATERIAL_ALPHATEST;
  45081. },
  45082. enumerable: true,
  45083. configurable: true
  45084. });
  45085. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45086. /**
  45087. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45088. */
  45089. get: function () {
  45090. return this._PBRMATERIAL_ALPHABLEND;
  45091. },
  45092. enumerable: true,
  45093. configurable: true
  45094. });
  45095. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45096. /**
  45097. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45098. * They are also discarded below the alpha cutoff threshold to improve performances.
  45099. */
  45100. get: function () {
  45101. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45102. },
  45103. enumerable: true,
  45104. configurable: true
  45105. });
  45106. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45107. /**
  45108. * Gets the image processing configuration used either in this material.
  45109. */
  45110. get: function () {
  45111. return this._imageProcessingConfiguration;
  45112. },
  45113. /**
  45114. * Sets the Default image processing configuration used either in the this material.
  45115. *
  45116. * If sets to null, the scene one is in use.
  45117. */
  45118. set: function (value) {
  45119. this._attachImageProcessingConfiguration(value);
  45120. // Ensure the effect will be rebuilt.
  45121. this._markAllSubMeshesAsTexturesDirty();
  45122. },
  45123. enumerable: true,
  45124. configurable: true
  45125. });
  45126. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45127. /**
  45128. * Gets wether the color curves effect is enabled.
  45129. */
  45130. get: function () {
  45131. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45132. },
  45133. /**
  45134. * Sets wether the color curves effect is enabled.
  45135. */
  45136. set: function (value) {
  45137. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45138. },
  45139. enumerable: true,
  45140. configurable: true
  45141. });
  45142. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45143. /**
  45144. * Gets wether the color grading effect is enabled.
  45145. */
  45146. get: function () {
  45147. return this.imageProcessingConfiguration.colorGradingEnabled;
  45148. },
  45149. /**
  45150. * Gets wether the color grading effect is enabled.
  45151. */
  45152. set: function (value) {
  45153. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45154. },
  45155. enumerable: true,
  45156. configurable: true
  45157. });
  45158. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45159. /**
  45160. * Gets wether tonemapping is enabled or not.
  45161. */
  45162. get: function () {
  45163. return this._imageProcessingConfiguration.toneMappingEnabled;
  45164. },
  45165. /**
  45166. * Sets wether tonemapping is enabled or not
  45167. */
  45168. set: function (value) {
  45169. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45170. },
  45171. enumerable: true,
  45172. configurable: true
  45173. });
  45174. ;
  45175. ;
  45176. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45177. /**
  45178. * The camera exposure used on this material.
  45179. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45180. * This corresponds to a photographic exposure.
  45181. */
  45182. get: function () {
  45183. return this._imageProcessingConfiguration.exposure;
  45184. },
  45185. /**
  45186. * The camera exposure used on this material.
  45187. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45188. * This corresponds to a photographic exposure.
  45189. */
  45190. set: function (value) {
  45191. this._imageProcessingConfiguration.exposure = value;
  45192. },
  45193. enumerable: true,
  45194. configurable: true
  45195. });
  45196. ;
  45197. ;
  45198. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45199. /**
  45200. * Gets The camera contrast used on this material.
  45201. */
  45202. get: function () {
  45203. return this._imageProcessingConfiguration.contrast;
  45204. },
  45205. /**
  45206. * Sets The camera contrast used on this material.
  45207. */
  45208. set: function (value) {
  45209. this._imageProcessingConfiguration.contrast = value;
  45210. },
  45211. enumerable: true,
  45212. configurable: true
  45213. });
  45214. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45215. /**
  45216. * Gets the Color Grading 2D Lookup Texture.
  45217. */
  45218. get: function () {
  45219. return this._imageProcessingConfiguration.colorGradingTexture;
  45220. },
  45221. /**
  45222. * Sets the Color Grading 2D Lookup Texture.
  45223. */
  45224. set: function (value) {
  45225. this._imageProcessingConfiguration.colorGradingTexture = value;
  45226. },
  45227. enumerable: true,
  45228. configurable: true
  45229. });
  45230. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45231. /**
  45232. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45233. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45234. * 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;
  45235. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45236. */
  45237. get: function () {
  45238. return this._imageProcessingConfiguration.colorCurves;
  45239. },
  45240. /**
  45241. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45242. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45243. * 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;
  45244. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45245. */
  45246. set: function (value) {
  45247. this._imageProcessingConfiguration.colorCurves = value;
  45248. },
  45249. enumerable: true,
  45250. configurable: true
  45251. });
  45252. /**
  45253. * Returns the name of this material class.
  45254. */
  45255. PBRMaterial.prototype.getClassName = function () {
  45256. return "PBRMaterial";
  45257. };
  45258. /**
  45259. * Returns an array of the actively used textures.
  45260. * @returns - Array of BaseTextures
  45261. */
  45262. PBRMaterial.prototype.getActiveTextures = function () {
  45263. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45264. if (this._albedoTexture) {
  45265. activeTextures.push(this._albedoTexture);
  45266. }
  45267. if (this._ambientTexture) {
  45268. activeTextures.push(this._ambientTexture);
  45269. }
  45270. if (this._opacityTexture) {
  45271. activeTextures.push(this._opacityTexture);
  45272. }
  45273. if (this._reflectionTexture) {
  45274. activeTextures.push(this._reflectionTexture);
  45275. }
  45276. if (this._emissiveTexture) {
  45277. activeTextures.push(this._emissiveTexture);
  45278. }
  45279. if (this._reflectivityTexture) {
  45280. activeTextures.push(this._reflectivityTexture);
  45281. }
  45282. if (this._metallicTexture) {
  45283. activeTextures.push(this._metallicTexture);
  45284. }
  45285. if (this._microSurfaceTexture) {
  45286. activeTextures.push(this._microSurfaceTexture);
  45287. }
  45288. if (this._bumpTexture) {
  45289. activeTextures.push(this._bumpTexture);
  45290. }
  45291. if (this._lightmapTexture) {
  45292. activeTextures.push(this._lightmapTexture);
  45293. }
  45294. if (this._refractionTexture) {
  45295. activeTextures.push(this._refractionTexture);
  45296. }
  45297. return activeTextures;
  45298. };
  45299. /**
  45300. * Checks to see if a texture is used in the material.
  45301. * @param texture - Base texture to use.
  45302. * @returns - Boolean specifying if a texture is used in the material.
  45303. */
  45304. PBRMaterial.prototype.hasTexture = function (texture) {
  45305. if (_super.prototype.hasTexture.call(this, texture)) {
  45306. return true;
  45307. }
  45308. if (this._albedoTexture === texture) {
  45309. return true;
  45310. }
  45311. if (this._ambientTexture === texture) {
  45312. return true;
  45313. }
  45314. if (this._opacityTexture === texture) {
  45315. return true;
  45316. }
  45317. if (this._reflectionTexture === texture) {
  45318. return true;
  45319. }
  45320. if (this._reflectivityTexture === texture) {
  45321. return true;
  45322. }
  45323. if (this._metallicTexture === texture) {
  45324. return true;
  45325. }
  45326. if (this._microSurfaceTexture === texture) {
  45327. return true;
  45328. }
  45329. if (this._bumpTexture === texture) {
  45330. return true;
  45331. }
  45332. if (this._lightmapTexture === texture) {
  45333. return true;
  45334. }
  45335. if (this._refractionTexture === texture) {
  45336. return true;
  45337. }
  45338. return false;
  45339. };
  45340. /**
  45341. * Makes a duplicate of the current material.
  45342. * @param name - name to use for the new material.
  45343. */
  45344. PBRMaterial.prototype.clone = function (name) {
  45345. var _this = this;
  45346. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45347. clone.id = name;
  45348. clone.name = name;
  45349. return clone;
  45350. };
  45351. /**
  45352. * Serializes this PBR Material.
  45353. * @returns - An object with the serialized material.
  45354. */
  45355. PBRMaterial.prototype.serialize = function () {
  45356. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45357. serializationObject.customType = "BABYLON.PBRMaterial";
  45358. return serializationObject;
  45359. };
  45360. // Statics
  45361. /**
  45362. * Parses a PBR Material from a serialized object.
  45363. * @param source - Serialized object.
  45364. * @param scene - BJS scene instance.
  45365. * @param rootUrl - url for the scene object
  45366. * @returns - PBRMaterial
  45367. */
  45368. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45369. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45370. };
  45371. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45372. /**
  45373. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45374. */
  45375. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45376. /**
  45377. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45378. */
  45379. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45380. /**
  45381. * 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.
  45382. * They are also discarded below the alpha cutoff threshold to improve performances.
  45383. */
  45384. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45385. __decorate([
  45386. BABYLON.serialize(),
  45387. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45388. ], PBRMaterial.prototype, "directIntensity", void 0);
  45389. __decorate([
  45390. BABYLON.serialize(),
  45391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45392. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45393. __decorate([
  45394. BABYLON.serialize(),
  45395. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45396. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45397. __decorate([
  45398. BABYLON.serialize(),
  45399. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45400. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45401. __decorate([
  45402. BABYLON.serialize(),
  45403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45404. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45405. __decorate([
  45406. BABYLON.serializeAsTexture(),
  45407. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45408. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45409. __decorate([
  45410. BABYLON.serializeAsTexture(),
  45411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45412. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45413. __decorate([
  45414. BABYLON.serialize(),
  45415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45416. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45417. __decorate([
  45418. BABYLON.serializeAsTexture(),
  45419. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45420. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45421. __decorate([
  45422. BABYLON.serializeAsTexture(),
  45423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45424. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45425. __decorate([
  45426. BABYLON.serializeAsTexture(),
  45427. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45428. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45429. __decorate([
  45430. BABYLON.serializeAsTexture(),
  45431. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45432. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45433. __decorate([
  45434. BABYLON.serializeAsTexture(),
  45435. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45436. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45437. __decorate([
  45438. BABYLON.serialize(),
  45439. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45440. ], PBRMaterial.prototype, "metallic", void 0);
  45441. __decorate([
  45442. BABYLON.serialize(),
  45443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45444. ], PBRMaterial.prototype, "roughness", void 0);
  45445. __decorate([
  45446. BABYLON.serializeAsTexture(),
  45447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45448. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45449. __decorate([
  45450. BABYLON.serializeAsTexture(),
  45451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45452. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45453. __decorate([
  45454. BABYLON.serializeAsTexture(),
  45455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45456. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45457. __decorate([
  45458. BABYLON.serializeAsTexture(),
  45459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45460. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45461. __decorate([
  45462. BABYLON.serializeAsColor3("ambient"),
  45463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45464. ], PBRMaterial.prototype, "ambientColor", void 0);
  45465. __decorate([
  45466. BABYLON.serializeAsColor3("albedo"),
  45467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45468. ], PBRMaterial.prototype, "albedoColor", void 0);
  45469. __decorate([
  45470. BABYLON.serializeAsColor3("reflectivity"),
  45471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45472. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45473. __decorate([
  45474. BABYLON.serializeAsColor3("reflection"),
  45475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45476. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45477. __decorate([
  45478. BABYLON.serializeAsColor3("emissive"),
  45479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45480. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45481. __decorate([
  45482. BABYLON.serialize(),
  45483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45484. ], PBRMaterial.prototype, "microSurface", void 0);
  45485. __decorate([
  45486. BABYLON.serialize(),
  45487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45488. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45489. __decorate([
  45490. BABYLON.serialize(),
  45491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45492. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45493. __decorate([
  45494. BABYLON.serialize(),
  45495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45496. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45497. __decorate([
  45498. BABYLON.serialize(),
  45499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45500. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45501. __decorate([
  45502. BABYLON.serialize(),
  45503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45504. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45505. __decorate([
  45506. BABYLON.serialize(),
  45507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45508. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45509. __decorate([
  45510. BABYLON.serialize(),
  45511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45512. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45513. __decorate([
  45514. BABYLON.serialize(),
  45515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45516. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45517. __decorate([
  45518. BABYLON.serialize(),
  45519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45520. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45521. __decorate([
  45522. BABYLON.serialize(),
  45523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45524. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45525. __decorate([
  45526. BABYLON.serialize(),
  45527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45528. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45529. __decorate([
  45530. BABYLON.serialize(),
  45531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45532. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45533. __decorate([
  45534. BABYLON.serialize(),
  45535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45536. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45537. __decorate([
  45538. BABYLON.serialize(),
  45539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45540. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45541. __decorate([
  45542. BABYLON.serialize(),
  45543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45544. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45545. __decorate([
  45546. BABYLON.serialize(),
  45547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45548. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45549. __decorate([
  45550. BABYLON.serialize(),
  45551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45552. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45553. __decorate([
  45554. BABYLON.serialize(),
  45555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45556. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45557. __decorate([
  45558. BABYLON.serialize(),
  45559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45560. ], PBRMaterial.prototype, "useParallax", void 0);
  45561. __decorate([
  45562. BABYLON.serialize(),
  45563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45564. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45565. __decorate([
  45566. BABYLON.serialize(),
  45567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45568. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45569. __decorate([
  45570. BABYLON.serialize(),
  45571. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45572. ], PBRMaterial.prototype, "disableLighting", void 0);
  45573. __decorate([
  45574. BABYLON.serialize(),
  45575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45576. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45577. __decorate([
  45578. BABYLON.serialize(),
  45579. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45580. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45581. __decorate([
  45582. BABYLON.serialize(),
  45583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45584. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45585. __decorate([
  45586. BABYLON.serialize(),
  45587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45588. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45589. __decorate([
  45590. BABYLON.serialize(),
  45591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45592. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45593. __decorate([
  45594. BABYLON.serialize(),
  45595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45596. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45597. __decorate([
  45598. BABYLON.serialize(),
  45599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45600. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45601. __decorate([
  45602. BABYLON.serializeAsTexture(),
  45603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45604. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45605. __decorate([
  45606. BABYLON.serialize(),
  45607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45608. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45609. __decorate([
  45610. BABYLON.serialize(),
  45611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45612. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45613. __decorate([
  45614. BABYLON.serialize(),
  45615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45616. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45617. __decorate([
  45618. BABYLON.serialize(),
  45619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45620. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45621. __decorate([
  45622. BABYLON.serialize(),
  45623. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45624. ], PBRMaterial.prototype, "unlit", void 0);
  45625. return PBRMaterial;
  45626. }(BABYLON.PBRBaseMaterial));
  45627. BABYLON.PBRMaterial = PBRMaterial;
  45628. })(BABYLON || (BABYLON = {}));
  45629. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45630. var BABYLON;
  45631. (function (BABYLON) {
  45632. /**
  45633. * The PBR material of BJS following the metal roughness convention.
  45634. *
  45635. * This fits to the PBR convention in the GLTF definition:
  45636. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45637. */
  45638. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45639. __extends(PBRMetallicRoughnessMaterial, _super);
  45640. /**
  45641. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45642. *
  45643. * @param name The material name
  45644. * @param scene The scene the material will be use in.
  45645. */
  45646. function PBRMetallicRoughnessMaterial(name, scene) {
  45647. var _this = _super.call(this, name, scene) || this;
  45648. _this._useRoughnessFromMetallicTextureAlpha = false;
  45649. _this._useRoughnessFromMetallicTextureGreen = true;
  45650. _this._useMetallnessFromMetallicTextureBlue = true;
  45651. _this.metallic = 1.0;
  45652. _this.roughness = 1.0;
  45653. return _this;
  45654. }
  45655. /**
  45656. * Return the currrent class name of the material.
  45657. */
  45658. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45659. return "PBRMetallicRoughnessMaterial";
  45660. };
  45661. /**
  45662. * Return the active textures of the material.
  45663. */
  45664. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45665. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45666. if (this.baseTexture) {
  45667. activeTextures.push(this.baseTexture);
  45668. }
  45669. if (this.metallicRoughnessTexture) {
  45670. activeTextures.push(this.metallicRoughnessTexture);
  45671. }
  45672. return activeTextures;
  45673. };
  45674. /**
  45675. * Checks to see if a texture is used in the material.
  45676. * @param texture - Base texture to use.
  45677. * @returns - Boolean specifying if a texture is used in the material.
  45678. */
  45679. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45680. if (_super.prototype.hasTexture.call(this, texture)) {
  45681. return true;
  45682. }
  45683. if (this.baseTexture === texture) {
  45684. return true;
  45685. }
  45686. if (this.metallicRoughnessTexture === texture) {
  45687. return true;
  45688. }
  45689. return false;
  45690. };
  45691. /**
  45692. * Makes a duplicate of the current material.
  45693. * @param name - name to use for the new material.
  45694. */
  45695. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45696. var _this = this;
  45697. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45698. clone.id = name;
  45699. clone.name = name;
  45700. return clone;
  45701. };
  45702. /**
  45703. * Serialize the material to a parsable JSON object.
  45704. */
  45705. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45706. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45707. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45708. return serializationObject;
  45709. };
  45710. /**
  45711. * Parses a JSON object correponding to the serialize function.
  45712. */
  45713. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45714. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45715. };
  45716. __decorate([
  45717. BABYLON.serializeAsColor3(),
  45718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45719. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45720. __decorate([
  45721. BABYLON.serializeAsTexture(),
  45722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45723. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45724. __decorate([
  45725. BABYLON.serialize(),
  45726. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45727. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45728. __decorate([
  45729. BABYLON.serialize(),
  45730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45731. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45732. __decorate([
  45733. BABYLON.serializeAsTexture(),
  45734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45735. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45736. return PBRMetallicRoughnessMaterial;
  45737. }(BABYLON.PBRBaseSimpleMaterial));
  45738. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45739. })(BABYLON || (BABYLON = {}));
  45740. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45741. var BABYLON;
  45742. (function (BABYLON) {
  45743. /**
  45744. * The PBR material of BJS following the specular glossiness convention.
  45745. *
  45746. * This fits to the PBR convention in the GLTF definition:
  45747. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45748. */
  45749. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45750. __extends(PBRSpecularGlossinessMaterial, _super);
  45751. /**
  45752. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45753. *
  45754. * @param name The material name
  45755. * @param scene The scene the material will be use in.
  45756. */
  45757. function PBRSpecularGlossinessMaterial(name, scene) {
  45758. var _this = _super.call(this, name, scene) || this;
  45759. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45760. return _this;
  45761. }
  45762. /**
  45763. * Return the currrent class name of the material.
  45764. */
  45765. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45766. return "PBRSpecularGlossinessMaterial";
  45767. };
  45768. /**
  45769. * Return the active textures of the material.
  45770. */
  45771. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45772. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45773. if (this.diffuseTexture) {
  45774. activeTextures.push(this.diffuseTexture);
  45775. }
  45776. if (this.specularGlossinessTexture) {
  45777. activeTextures.push(this.specularGlossinessTexture);
  45778. }
  45779. return activeTextures;
  45780. };
  45781. /**
  45782. * Checks to see if a texture is used in the material.
  45783. * @param texture - Base texture to use.
  45784. * @returns - Boolean specifying if a texture is used in the material.
  45785. */
  45786. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45787. if (_super.prototype.hasTexture.call(this, texture)) {
  45788. return true;
  45789. }
  45790. if (this.diffuseTexture === texture) {
  45791. return true;
  45792. }
  45793. if (this.specularGlossinessTexture === texture) {
  45794. return true;
  45795. }
  45796. return false;
  45797. };
  45798. /**
  45799. * Makes a duplicate of the current material.
  45800. * @param name - name to use for the new material.
  45801. */
  45802. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45803. var _this = this;
  45804. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45805. clone.id = name;
  45806. clone.name = name;
  45807. return clone;
  45808. };
  45809. /**
  45810. * Serialize the material to a parsable JSON object.
  45811. */
  45812. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45813. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45814. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45815. return serializationObject;
  45816. };
  45817. /**
  45818. * Parses a JSON object correponding to the serialize function.
  45819. */
  45820. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45821. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45822. };
  45823. __decorate([
  45824. BABYLON.serializeAsColor3("diffuse"),
  45825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45826. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45827. __decorate([
  45828. BABYLON.serializeAsTexture(),
  45829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45830. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45831. __decorate([
  45832. BABYLON.serializeAsColor3("specular"),
  45833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45834. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45835. __decorate([
  45836. BABYLON.serialize(),
  45837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45838. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45839. __decorate([
  45840. BABYLON.serializeAsTexture(),
  45841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45842. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45843. return PBRSpecularGlossinessMaterial;
  45844. }(BABYLON.PBRBaseSimpleMaterial));
  45845. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45846. })(BABYLON || (BABYLON = {}));
  45847. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45848. var BABYLON;
  45849. (function (BABYLON) {
  45850. BABYLON.CameraInputTypes = {};
  45851. var CameraInputsManager = /** @class */ (function () {
  45852. function CameraInputsManager(camera) {
  45853. this.attached = {};
  45854. this.camera = camera;
  45855. this.checkInputs = function () { };
  45856. }
  45857. /**
  45858. * Add an input method to a camera.
  45859. * builtin inputs example: camera.inputs.addGamepad();
  45860. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45861. * @param input camera input method
  45862. */
  45863. CameraInputsManager.prototype.add = function (input) {
  45864. var type = input.getSimpleName();
  45865. if (this.attached[type]) {
  45866. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45867. return;
  45868. }
  45869. this.attached[type] = input;
  45870. input.camera = this.camera;
  45871. //for checkInputs, we are dynamically creating a function
  45872. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45873. if (input.checkInputs) {
  45874. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45875. }
  45876. if (this.attachedElement) {
  45877. input.attachControl(this.attachedElement);
  45878. }
  45879. };
  45880. /**
  45881. * Remove a specific input method from a camera
  45882. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45883. * @param inputToRemove camera input method
  45884. */
  45885. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45886. for (var cam in this.attached) {
  45887. var input = this.attached[cam];
  45888. if (input === inputToRemove) {
  45889. input.detachControl(this.attachedElement);
  45890. input.camera = null;
  45891. delete this.attached[cam];
  45892. this.rebuildInputCheck();
  45893. }
  45894. }
  45895. };
  45896. CameraInputsManager.prototype.removeByType = function (inputType) {
  45897. for (var cam in this.attached) {
  45898. var input = this.attached[cam];
  45899. if (input.getClassName() === inputType) {
  45900. input.detachControl(this.attachedElement);
  45901. input.camera = null;
  45902. delete this.attached[cam];
  45903. this.rebuildInputCheck();
  45904. }
  45905. }
  45906. };
  45907. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45908. var current = this.checkInputs;
  45909. return function () {
  45910. current();
  45911. fn();
  45912. };
  45913. };
  45914. CameraInputsManager.prototype.attachInput = function (input) {
  45915. if (this.attachedElement) {
  45916. input.attachControl(this.attachedElement, this.noPreventDefault);
  45917. }
  45918. };
  45919. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45920. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45921. if (this.attachedElement) {
  45922. return;
  45923. }
  45924. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45925. this.attachedElement = element;
  45926. this.noPreventDefault = noPreventDefault;
  45927. for (var cam in this.attached) {
  45928. this.attached[cam].attachControl(element, noPreventDefault);
  45929. }
  45930. };
  45931. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45932. if (disconnect === void 0) { disconnect = false; }
  45933. if (this.attachedElement !== element) {
  45934. return;
  45935. }
  45936. for (var cam in this.attached) {
  45937. this.attached[cam].detachControl(element);
  45938. if (disconnect) {
  45939. this.attached[cam].camera = null;
  45940. }
  45941. }
  45942. this.attachedElement = null;
  45943. };
  45944. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45945. this.checkInputs = function () { };
  45946. for (var cam in this.attached) {
  45947. var input = this.attached[cam];
  45948. if (input.checkInputs) {
  45949. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45950. }
  45951. }
  45952. };
  45953. /**
  45954. * Remove all attached input methods from a camera
  45955. */
  45956. CameraInputsManager.prototype.clear = function () {
  45957. if (this.attachedElement) {
  45958. this.detachElement(this.attachedElement, true);
  45959. }
  45960. this.attached = {};
  45961. this.attachedElement = null;
  45962. this.checkInputs = function () { };
  45963. };
  45964. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  45965. var inputs = {};
  45966. for (var cam in this.attached) {
  45967. var input = this.attached[cam];
  45968. var res = BABYLON.SerializationHelper.Serialize(input);
  45969. inputs[input.getClassName()] = res;
  45970. }
  45971. serializedCamera.inputsmgr = inputs;
  45972. };
  45973. CameraInputsManager.prototype.parse = function (parsedCamera) {
  45974. var parsedInputs = parsedCamera.inputsmgr;
  45975. if (parsedInputs) {
  45976. this.clear();
  45977. for (var n in parsedInputs) {
  45978. var construct = BABYLON.CameraInputTypes[n];
  45979. if (construct) {
  45980. var parsedinput = parsedInputs[n];
  45981. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  45982. this.add(input);
  45983. }
  45984. }
  45985. }
  45986. else {
  45987. //2016-03-08 this part is for managing backward compatibility
  45988. for (var n in this.attached) {
  45989. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  45990. if (construct) {
  45991. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  45992. this.remove(this.attached[n]);
  45993. this.add(input);
  45994. }
  45995. }
  45996. }
  45997. };
  45998. return CameraInputsManager;
  45999. }());
  46000. BABYLON.CameraInputsManager = CameraInputsManager;
  46001. })(BABYLON || (BABYLON = {}));
  46002. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46003. var BABYLON;
  46004. (function (BABYLON) {
  46005. var TargetCamera = /** @class */ (function (_super) {
  46006. __extends(TargetCamera, _super);
  46007. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46008. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46009. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46010. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46011. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46012. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46013. _this.speed = 2.0;
  46014. _this.noRotationConstraint = false;
  46015. _this.lockedTarget = null;
  46016. _this._currentTarget = BABYLON.Vector3.Zero();
  46017. _this._viewMatrix = BABYLON.Matrix.Zero();
  46018. _this._camMatrix = BABYLON.Matrix.Zero();
  46019. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46020. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46021. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46022. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46023. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46024. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46025. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46026. return _this;
  46027. }
  46028. TargetCamera.prototype.getFrontPosition = function (distance) {
  46029. this.getWorldMatrix();
  46030. var direction = this.getTarget().subtract(this.position);
  46031. direction.normalize();
  46032. direction.scaleInPlace(distance);
  46033. return this.globalPosition.add(direction);
  46034. };
  46035. TargetCamera.prototype._getLockedTargetPosition = function () {
  46036. if (!this.lockedTarget) {
  46037. return null;
  46038. }
  46039. if (this.lockedTarget.absolutePosition) {
  46040. this.lockedTarget.computeWorldMatrix();
  46041. }
  46042. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46043. };
  46044. TargetCamera.prototype.storeState = function () {
  46045. this._storedPosition = this.position.clone();
  46046. this._storedRotation = this.rotation.clone();
  46047. if (this.rotationQuaternion) {
  46048. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46049. }
  46050. return _super.prototype.storeState.call(this);
  46051. };
  46052. /**
  46053. * Restored camera state. You must call storeState() first
  46054. */
  46055. TargetCamera.prototype._restoreStateValues = function () {
  46056. if (!_super.prototype._restoreStateValues.call(this)) {
  46057. return false;
  46058. }
  46059. this.position = this._storedPosition.clone();
  46060. this.rotation = this._storedRotation.clone();
  46061. if (this.rotationQuaternion) {
  46062. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46063. }
  46064. this.cameraDirection.copyFromFloats(0, 0, 0);
  46065. this.cameraRotation.copyFromFloats(0, 0);
  46066. return true;
  46067. };
  46068. // Cache
  46069. TargetCamera.prototype._initCache = function () {
  46070. _super.prototype._initCache.call(this);
  46071. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46072. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46073. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46074. };
  46075. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46076. if (!ignoreParentClass) {
  46077. _super.prototype._updateCache.call(this);
  46078. }
  46079. var lockedTargetPosition = this._getLockedTargetPosition();
  46080. if (!lockedTargetPosition) {
  46081. this._cache.lockedTarget = null;
  46082. }
  46083. else {
  46084. if (!this._cache.lockedTarget) {
  46085. this._cache.lockedTarget = lockedTargetPosition.clone();
  46086. }
  46087. else {
  46088. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46089. }
  46090. }
  46091. this._cache.rotation.copyFrom(this.rotation);
  46092. if (this.rotationQuaternion)
  46093. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46094. };
  46095. // Synchronized
  46096. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46097. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46098. return false;
  46099. }
  46100. var lockedTargetPosition = this._getLockedTargetPosition();
  46101. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46102. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46103. };
  46104. // Methods
  46105. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46106. var engine = this.getEngine();
  46107. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46108. };
  46109. // Target
  46110. TargetCamera.prototype.setTarget = function (target) {
  46111. this.upVector.normalize();
  46112. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46113. this._camMatrix.invert();
  46114. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46115. var vDir = target.subtract(this.position);
  46116. if (vDir.x >= 0.0) {
  46117. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46118. }
  46119. else {
  46120. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46121. }
  46122. this.rotation.z = 0;
  46123. if (isNaN(this.rotation.x)) {
  46124. this.rotation.x = 0;
  46125. }
  46126. if (isNaN(this.rotation.y)) {
  46127. this.rotation.y = 0;
  46128. }
  46129. if (isNaN(this.rotation.z)) {
  46130. this.rotation.z = 0;
  46131. }
  46132. if (this.rotationQuaternion) {
  46133. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46134. }
  46135. };
  46136. /**
  46137. * Return the current target position of the camera. This value is expressed in local space.
  46138. */
  46139. TargetCamera.prototype.getTarget = function () {
  46140. return this._currentTarget;
  46141. };
  46142. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46143. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46144. };
  46145. TargetCamera.prototype._updatePosition = function () {
  46146. if (this.parent) {
  46147. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46148. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46149. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46150. return;
  46151. }
  46152. this.position.addInPlace(this.cameraDirection);
  46153. };
  46154. TargetCamera.prototype._checkInputs = function () {
  46155. var needToMove = this._decideIfNeedsToMove();
  46156. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46157. // Move
  46158. if (needToMove) {
  46159. this._updatePosition();
  46160. }
  46161. // Rotate
  46162. if (needToRotate) {
  46163. this.rotation.x += this.cameraRotation.x;
  46164. this.rotation.y += this.cameraRotation.y;
  46165. //rotate, if quaternion is set and rotation was used
  46166. if (this.rotationQuaternion) {
  46167. var len = this.rotation.lengthSquared();
  46168. if (len) {
  46169. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46170. }
  46171. }
  46172. if (!this.noRotationConstraint) {
  46173. var limit = (Math.PI / 2) * 0.95;
  46174. if (this.rotation.x > limit)
  46175. this.rotation.x = limit;
  46176. if (this.rotation.x < -limit)
  46177. this.rotation.x = -limit;
  46178. }
  46179. }
  46180. // Inertia
  46181. if (needToMove) {
  46182. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46183. this.cameraDirection.x = 0;
  46184. }
  46185. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46186. this.cameraDirection.y = 0;
  46187. }
  46188. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46189. this.cameraDirection.z = 0;
  46190. }
  46191. this.cameraDirection.scaleInPlace(this.inertia);
  46192. }
  46193. if (needToRotate) {
  46194. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46195. this.cameraRotation.x = 0;
  46196. }
  46197. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46198. this.cameraRotation.y = 0;
  46199. }
  46200. this.cameraRotation.scaleInPlace(this.inertia);
  46201. }
  46202. _super.prototype._checkInputs.call(this);
  46203. };
  46204. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46205. if (this.rotationQuaternion) {
  46206. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46207. }
  46208. else {
  46209. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46210. }
  46211. //update the up vector!
  46212. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46213. };
  46214. TargetCamera.prototype._getViewMatrix = function () {
  46215. if (this.lockedTarget) {
  46216. this.setTarget(this._getLockedTargetPosition());
  46217. }
  46218. // Compute
  46219. this._updateCameraRotationMatrix();
  46220. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46221. // Computing target and final matrix
  46222. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46223. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46224. return this._viewMatrix;
  46225. };
  46226. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46227. if (this.parent) {
  46228. var parentWorldMatrix = this.parent.getWorldMatrix();
  46229. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46230. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46231. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46232. this._markSyncedWithParent();
  46233. }
  46234. else {
  46235. this._globalPosition.copyFrom(this.position);
  46236. this._globalCurrentTarget.copyFrom(target);
  46237. this._globalCurrentUpVector.copyFrom(up);
  46238. }
  46239. if (this.getScene().useRightHandedSystem) {
  46240. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46241. }
  46242. else {
  46243. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46244. }
  46245. };
  46246. /**
  46247. * @override
  46248. * Override Camera.createRigCamera
  46249. */
  46250. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46251. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46252. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46253. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46254. if (!this.rotationQuaternion) {
  46255. this.rotationQuaternion = new BABYLON.Quaternion();
  46256. }
  46257. rigCamera._cameraRigParams = {};
  46258. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46259. }
  46260. return rigCamera;
  46261. }
  46262. return null;
  46263. };
  46264. /**
  46265. * @override
  46266. * Override Camera._updateRigCameras
  46267. */
  46268. TargetCamera.prototype._updateRigCameras = function () {
  46269. var camLeft = this._rigCameras[0];
  46270. var camRight = this._rigCameras[1];
  46271. switch (this.cameraRigMode) {
  46272. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46273. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46274. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46275. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46276. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46277. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46278. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46279. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46280. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46281. camLeft.setTarget(this.getTarget());
  46282. camRight.setTarget(this.getTarget());
  46283. break;
  46284. case BABYLON.Camera.RIG_MODE_VR:
  46285. if (camLeft.rotationQuaternion) {
  46286. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46287. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46288. }
  46289. else {
  46290. camLeft.rotation.copyFrom(this.rotation);
  46291. camRight.rotation.copyFrom(this.rotation);
  46292. }
  46293. camLeft.position.copyFrom(this.position);
  46294. camRight.position.copyFrom(this.position);
  46295. break;
  46296. }
  46297. _super.prototype._updateRigCameras.call(this);
  46298. };
  46299. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46300. if (!this._rigCamTransformMatrix) {
  46301. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46302. }
  46303. var target = this.getTarget();
  46304. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46305. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46306. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46307. };
  46308. TargetCamera.prototype.getClassName = function () {
  46309. return "TargetCamera";
  46310. };
  46311. __decorate([
  46312. BABYLON.serializeAsVector3()
  46313. ], TargetCamera.prototype, "rotation", void 0);
  46314. __decorate([
  46315. BABYLON.serialize()
  46316. ], TargetCamera.prototype, "speed", void 0);
  46317. __decorate([
  46318. BABYLON.serializeAsMeshReference("lockedTargetId")
  46319. ], TargetCamera.prototype, "lockedTarget", void 0);
  46320. return TargetCamera;
  46321. }(BABYLON.Camera));
  46322. BABYLON.TargetCamera = TargetCamera;
  46323. })(BABYLON || (BABYLON = {}));
  46324. //# sourceMappingURL=babylon.targetCamera.js.map
  46325. var BABYLON;
  46326. (function (BABYLON) {
  46327. var FreeCameraMouseInput = /** @class */ (function () {
  46328. function FreeCameraMouseInput(touchEnabled) {
  46329. if (touchEnabled === void 0) { touchEnabled = true; }
  46330. this.touchEnabled = touchEnabled;
  46331. this.buttons = [0, 1, 2];
  46332. this.angularSensibility = 2000.0;
  46333. this.previousPosition = null;
  46334. }
  46335. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46336. var _this = this;
  46337. var engine = this.camera.getEngine();
  46338. if (!this._pointerInput) {
  46339. this._pointerInput = function (p, s) {
  46340. var evt = p.event;
  46341. if (engine.isInVRExclusivePointerMode) {
  46342. return;
  46343. }
  46344. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46345. return;
  46346. }
  46347. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46348. return;
  46349. }
  46350. var srcElement = (evt.srcElement || evt.target);
  46351. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46352. try {
  46353. srcElement.setPointerCapture(evt.pointerId);
  46354. }
  46355. catch (e) {
  46356. //Nothing to do with the error. Execution will continue.
  46357. }
  46358. _this.previousPosition = {
  46359. x: evt.clientX,
  46360. y: evt.clientY
  46361. };
  46362. if (!noPreventDefault) {
  46363. evt.preventDefault();
  46364. element.focus();
  46365. }
  46366. }
  46367. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46368. try {
  46369. srcElement.releasePointerCapture(evt.pointerId);
  46370. }
  46371. catch (e) {
  46372. //Nothing to do with the error.
  46373. }
  46374. _this.previousPosition = null;
  46375. if (!noPreventDefault) {
  46376. evt.preventDefault();
  46377. }
  46378. }
  46379. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46380. if (!_this.previousPosition || engine.isPointerLock) {
  46381. return;
  46382. }
  46383. var offsetX = evt.clientX - _this.previousPosition.x;
  46384. if (_this.camera.getScene().useRightHandedSystem)
  46385. offsetX *= -1;
  46386. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46387. offsetX *= -1;
  46388. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46389. var offsetY = evt.clientY - _this.previousPosition.y;
  46390. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46391. _this.previousPosition = {
  46392. x: evt.clientX,
  46393. y: evt.clientY
  46394. };
  46395. if (!noPreventDefault) {
  46396. evt.preventDefault();
  46397. }
  46398. }
  46399. };
  46400. }
  46401. this._onMouseMove = function (evt) {
  46402. if (!engine.isPointerLock) {
  46403. return;
  46404. }
  46405. if (engine.isInVRExclusivePointerMode) {
  46406. return;
  46407. }
  46408. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46409. if (_this.camera.getScene().useRightHandedSystem)
  46410. offsetX *= -1;
  46411. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46412. offsetX *= -1;
  46413. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46414. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46415. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46416. _this.previousPosition = null;
  46417. if (!noPreventDefault) {
  46418. evt.preventDefault();
  46419. }
  46420. };
  46421. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46422. element.addEventListener("mousemove", this._onMouseMove, false);
  46423. };
  46424. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46425. if (this._observer && element) {
  46426. this.camera.getScene().onPointerObservable.remove(this._observer);
  46427. if (this._onMouseMove) {
  46428. element.removeEventListener("mousemove", this._onMouseMove);
  46429. }
  46430. this._observer = null;
  46431. this._onMouseMove = null;
  46432. this.previousPosition = null;
  46433. }
  46434. };
  46435. FreeCameraMouseInput.prototype.getClassName = function () {
  46436. return "FreeCameraMouseInput";
  46437. };
  46438. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46439. return "mouse";
  46440. };
  46441. __decorate([
  46442. BABYLON.serialize()
  46443. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46444. __decorate([
  46445. BABYLON.serialize()
  46446. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46447. return FreeCameraMouseInput;
  46448. }());
  46449. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46450. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46451. })(BABYLON || (BABYLON = {}));
  46452. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46453. var BABYLON;
  46454. (function (BABYLON) {
  46455. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46456. function FreeCameraKeyboardMoveInput() {
  46457. this._keys = new Array();
  46458. this.keysUp = [38];
  46459. this.keysDown = [40];
  46460. this.keysLeft = [37];
  46461. this.keysRight = [39];
  46462. }
  46463. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46464. var _this = this;
  46465. if (this._onCanvasBlurObserver) {
  46466. return;
  46467. }
  46468. this._scene = this.camera.getScene();
  46469. this._engine = this._scene.getEngine();
  46470. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46471. _this._keys = [];
  46472. });
  46473. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46474. var evt = info.event;
  46475. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46476. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46477. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46478. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46479. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46480. var index = _this._keys.indexOf(evt.keyCode);
  46481. if (index === -1) {
  46482. _this._keys.push(evt.keyCode);
  46483. }
  46484. if (!noPreventDefault) {
  46485. evt.preventDefault();
  46486. }
  46487. }
  46488. }
  46489. else {
  46490. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46491. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46492. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46493. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46494. var index = _this._keys.indexOf(evt.keyCode);
  46495. if (index >= 0) {
  46496. _this._keys.splice(index, 1);
  46497. }
  46498. if (!noPreventDefault) {
  46499. evt.preventDefault();
  46500. }
  46501. }
  46502. }
  46503. });
  46504. };
  46505. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46506. if (this._scene) {
  46507. if (this._onKeyboardObserver) {
  46508. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46509. }
  46510. if (this._onCanvasBlurObserver) {
  46511. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46512. }
  46513. this._onKeyboardObserver = null;
  46514. this._onCanvasBlurObserver = null;
  46515. }
  46516. this._keys = [];
  46517. };
  46518. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46519. if (this._onKeyboardObserver) {
  46520. var camera = this.camera;
  46521. // Keyboard
  46522. for (var index = 0; index < this._keys.length; index++) {
  46523. var keyCode = this._keys[index];
  46524. var speed = camera._computeLocalCameraSpeed();
  46525. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46526. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46527. }
  46528. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46529. camera._localDirection.copyFromFloats(0, 0, speed);
  46530. }
  46531. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46532. camera._localDirection.copyFromFloats(speed, 0, 0);
  46533. }
  46534. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46535. camera._localDirection.copyFromFloats(0, 0, -speed);
  46536. }
  46537. if (camera.getScene().useRightHandedSystem) {
  46538. camera._localDirection.z *= -1;
  46539. }
  46540. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46541. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46542. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46543. }
  46544. }
  46545. };
  46546. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46547. return "FreeCameraKeyboardMoveInput";
  46548. };
  46549. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46550. this._keys = [];
  46551. };
  46552. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46553. return "keyboard";
  46554. };
  46555. __decorate([
  46556. BABYLON.serialize()
  46557. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46558. __decorate([
  46559. BABYLON.serialize()
  46560. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46561. __decorate([
  46562. BABYLON.serialize()
  46563. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46564. __decorate([
  46565. BABYLON.serialize()
  46566. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46567. return FreeCameraKeyboardMoveInput;
  46568. }());
  46569. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46570. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46571. })(BABYLON || (BABYLON = {}));
  46572. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46573. var BABYLON;
  46574. (function (BABYLON) {
  46575. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46576. __extends(FreeCameraInputsManager, _super);
  46577. function FreeCameraInputsManager(camera) {
  46578. return _super.call(this, camera) || this;
  46579. }
  46580. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46581. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46582. return this;
  46583. };
  46584. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46585. if (touchEnabled === void 0) { touchEnabled = true; }
  46586. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46587. return this;
  46588. };
  46589. FreeCameraInputsManager.prototype.addGamepad = function () {
  46590. this.add(new BABYLON.FreeCameraGamepadInput());
  46591. return this;
  46592. };
  46593. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46594. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46595. return this;
  46596. };
  46597. FreeCameraInputsManager.prototype.addTouch = function () {
  46598. this.add(new BABYLON.FreeCameraTouchInput());
  46599. return this;
  46600. };
  46601. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46602. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46603. return this;
  46604. };
  46605. return FreeCameraInputsManager;
  46606. }(BABYLON.CameraInputsManager));
  46607. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46608. })(BABYLON || (BABYLON = {}));
  46609. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46610. var BABYLON;
  46611. (function (BABYLON) {
  46612. var FreeCamera = /** @class */ (function (_super) {
  46613. __extends(FreeCamera, _super);
  46614. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46615. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46616. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46617. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46618. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46619. _this.checkCollisions = false;
  46620. _this.applyGravity = false;
  46621. _this._needMoveForGravity = false;
  46622. _this._oldPosition = BABYLON.Vector3.Zero();
  46623. _this._diffPosition = BABYLON.Vector3.Zero();
  46624. _this._newPosition = BABYLON.Vector3.Zero();
  46625. // Collisions
  46626. _this._collisionMask = -1;
  46627. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46628. if (collidedMesh === void 0) { collidedMesh = null; }
  46629. //TODO move this to the collision coordinator!
  46630. if (_this.getScene().workerCollisions)
  46631. newPosition.multiplyInPlace(_this._collider._radius);
  46632. var updatePosition = function (newPos) {
  46633. _this._newPosition.copyFrom(newPos);
  46634. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46635. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46636. _this.position.addInPlace(_this._diffPosition);
  46637. if (_this.onCollide && collidedMesh) {
  46638. _this.onCollide(collidedMesh);
  46639. }
  46640. }
  46641. };
  46642. updatePosition(newPosition);
  46643. };
  46644. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46645. _this.inputs.addKeyboard().addMouse();
  46646. return _this;
  46647. }
  46648. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46649. //-- begin properties for backward compatibility for inputs
  46650. /**
  46651. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46652. * Higher values reduce sensitivity.
  46653. */
  46654. get: function () {
  46655. var mouse = this.inputs.attached["mouse"];
  46656. if (mouse)
  46657. return mouse.angularSensibility;
  46658. return 0;
  46659. },
  46660. /**
  46661. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46662. * Higher values reduce sensitivity.
  46663. */
  46664. set: function (value) {
  46665. var mouse = this.inputs.attached["mouse"];
  46666. if (mouse)
  46667. mouse.angularSensibility = value;
  46668. },
  46669. enumerable: true,
  46670. configurable: true
  46671. });
  46672. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46673. get: function () {
  46674. var keyboard = this.inputs.attached["keyboard"];
  46675. if (keyboard)
  46676. return keyboard.keysUp;
  46677. return [];
  46678. },
  46679. set: function (value) {
  46680. var keyboard = this.inputs.attached["keyboard"];
  46681. if (keyboard)
  46682. keyboard.keysUp = value;
  46683. },
  46684. enumerable: true,
  46685. configurable: true
  46686. });
  46687. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46688. get: function () {
  46689. var keyboard = this.inputs.attached["keyboard"];
  46690. if (keyboard)
  46691. return keyboard.keysDown;
  46692. return [];
  46693. },
  46694. set: function (value) {
  46695. var keyboard = this.inputs.attached["keyboard"];
  46696. if (keyboard)
  46697. keyboard.keysDown = value;
  46698. },
  46699. enumerable: true,
  46700. configurable: true
  46701. });
  46702. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46703. get: function () {
  46704. var keyboard = this.inputs.attached["keyboard"];
  46705. if (keyboard)
  46706. return keyboard.keysLeft;
  46707. return [];
  46708. },
  46709. set: function (value) {
  46710. var keyboard = this.inputs.attached["keyboard"];
  46711. if (keyboard)
  46712. keyboard.keysLeft = value;
  46713. },
  46714. enumerable: true,
  46715. configurable: true
  46716. });
  46717. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46718. get: function () {
  46719. var keyboard = this.inputs.attached["keyboard"];
  46720. if (keyboard)
  46721. return keyboard.keysRight;
  46722. return [];
  46723. },
  46724. set: function (value) {
  46725. var keyboard = this.inputs.attached["keyboard"];
  46726. if (keyboard)
  46727. keyboard.keysRight = value;
  46728. },
  46729. enumerable: true,
  46730. configurable: true
  46731. });
  46732. // Controls
  46733. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46734. this.inputs.attachElement(element, noPreventDefault);
  46735. };
  46736. FreeCamera.prototype.detachControl = function (element) {
  46737. this.inputs.detachElement(element);
  46738. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46739. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46740. };
  46741. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46742. get: function () {
  46743. return this._collisionMask;
  46744. },
  46745. set: function (mask) {
  46746. this._collisionMask = !isNaN(mask) ? mask : -1;
  46747. },
  46748. enumerable: true,
  46749. configurable: true
  46750. });
  46751. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46752. var globalPosition;
  46753. if (this.parent) {
  46754. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46755. }
  46756. else {
  46757. globalPosition = this.position;
  46758. }
  46759. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46760. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46761. if (!this._collider) {
  46762. this._collider = new BABYLON.Collider();
  46763. }
  46764. this._collider._radius = this.ellipsoid;
  46765. this._collider.collisionMask = this._collisionMask;
  46766. //no need for clone, as long as gravity is not on.
  46767. var actualDisplacement = displacement;
  46768. //add gravity to the direction to prevent the dual-collision checking
  46769. if (this.applyGravity) {
  46770. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46771. actualDisplacement = displacement.add(this.getScene().gravity);
  46772. }
  46773. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46774. };
  46775. FreeCamera.prototype._checkInputs = function () {
  46776. if (!this._localDirection) {
  46777. this._localDirection = BABYLON.Vector3.Zero();
  46778. this._transformedDirection = BABYLON.Vector3.Zero();
  46779. }
  46780. this.inputs.checkInputs();
  46781. _super.prototype._checkInputs.call(this);
  46782. };
  46783. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46784. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46785. };
  46786. FreeCamera.prototype._updatePosition = function () {
  46787. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46788. this._collideWithWorld(this.cameraDirection);
  46789. }
  46790. else {
  46791. _super.prototype._updatePosition.call(this);
  46792. }
  46793. };
  46794. FreeCamera.prototype.dispose = function () {
  46795. this.inputs.clear();
  46796. _super.prototype.dispose.call(this);
  46797. };
  46798. FreeCamera.prototype.getClassName = function () {
  46799. return "FreeCamera";
  46800. };
  46801. __decorate([
  46802. BABYLON.serializeAsVector3()
  46803. ], FreeCamera.prototype, "ellipsoid", void 0);
  46804. __decorate([
  46805. BABYLON.serializeAsVector3()
  46806. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46807. __decorate([
  46808. BABYLON.serialize()
  46809. ], FreeCamera.prototype, "checkCollisions", void 0);
  46810. __decorate([
  46811. BABYLON.serialize()
  46812. ], FreeCamera.prototype, "applyGravity", void 0);
  46813. return FreeCamera;
  46814. }(BABYLON.TargetCamera));
  46815. BABYLON.FreeCamera = FreeCamera;
  46816. })(BABYLON || (BABYLON = {}));
  46817. //# sourceMappingURL=babylon.freeCamera.js.map
  46818. var BABYLON;
  46819. (function (BABYLON) {
  46820. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46821. function ArcRotateCameraKeyboardMoveInput() {
  46822. this._keys = new Array();
  46823. this.keysUp = [38];
  46824. this.keysDown = [40];
  46825. this.keysLeft = [37];
  46826. this.keysRight = [39];
  46827. this.keysReset = [220];
  46828. this.panningSensibility = 50.0;
  46829. this.zoomingSensibility = 25.0;
  46830. this.useAltToZoom = true;
  46831. }
  46832. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46833. var _this = this;
  46834. if (this._onCanvasBlurObserver) {
  46835. return;
  46836. }
  46837. this._scene = this.camera.getScene();
  46838. this._engine = this._scene.getEngine();
  46839. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46840. _this._keys = [];
  46841. });
  46842. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46843. var evt = info.event;
  46844. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46845. _this._ctrlPressed = evt.ctrlKey;
  46846. _this._altPressed = evt.altKey;
  46847. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46848. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46849. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46850. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46851. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46852. var index = _this._keys.indexOf(evt.keyCode);
  46853. if (index === -1) {
  46854. _this._keys.push(evt.keyCode);
  46855. }
  46856. if (evt.preventDefault) {
  46857. if (!noPreventDefault) {
  46858. evt.preventDefault();
  46859. }
  46860. }
  46861. }
  46862. }
  46863. else {
  46864. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46865. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46866. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46867. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46868. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46869. var index = _this._keys.indexOf(evt.keyCode);
  46870. if (index >= 0) {
  46871. _this._keys.splice(index, 1);
  46872. }
  46873. if (evt.preventDefault) {
  46874. if (!noPreventDefault) {
  46875. evt.preventDefault();
  46876. }
  46877. }
  46878. }
  46879. }
  46880. });
  46881. };
  46882. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46883. if (this._scene) {
  46884. if (this._onKeyboardObserver) {
  46885. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46886. }
  46887. if (this._onCanvasBlurObserver) {
  46888. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46889. }
  46890. this._onKeyboardObserver = null;
  46891. this._onCanvasBlurObserver = null;
  46892. }
  46893. this._keys = [];
  46894. };
  46895. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46896. if (this._onKeyboardObserver) {
  46897. var camera = this.camera;
  46898. for (var index = 0; index < this._keys.length; index++) {
  46899. var keyCode = this._keys[index];
  46900. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46901. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46902. camera.inertialPanningX -= 1 / this.panningSensibility;
  46903. }
  46904. else {
  46905. camera.inertialAlphaOffset -= 0.01;
  46906. }
  46907. }
  46908. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46909. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46910. camera.inertialPanningY += 1 / this.panningSensibility;
  46911. }
  46912. else if (this._altPressed && this.useAltToZoom) {
  46913. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46914. }
  46915. else {
  46916. camera.inertialBetaOffset -= 0.01;
  46917. }
  46918. }
  46919. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46920. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46921. camera.inertialPanningX += 1 / this.panningSensibility;
  46922. }
  46923. else {
  46924. camera.inertialAlphaOffset += 0.01;
  46925. }
  46926. }
  46927. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46928. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46929. camera.inertialPanningY -= 1 / this.panningSensibility;
  46930. }
  46931. else if (this._altPressed && this.useAltToZoom) {
  46932. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46933. }
  46934. else {
  46935. camera.inertialBetaOffset += 0.01;
  46936. }
  46937. }
  46938. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46939. camera.restoreState();
  46940. }
  46941. }
  46942. }
  46943. };
  46944. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46945. return "ArcRotateCameraKeyboardMoveInput";
  46946. };
  46947. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46948. return "keyboard";
  46949. };
  46950. __decorate([
  46951. BABYLON.serialize()
  46952. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46953. __decorate([
  46954. BABYLON.serialize()
  46955. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46956. __decorate([
  46957. BABYLON.serialize()
  46958. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46959. __decorate([
  46960. BABYLON.serialize()
  46961. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46962. __decorate([
  46963. BABYLON.serialize()
  46964. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  46965. __decorate([
  46966. BABYLON.serialize()
  46967. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  46968. __decorate([
  46969. BABYLON.serialize()
  46970. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  46971. __decorate([
  46972. BABYLON.serialize()
  46973. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  46974. return ArcRotateCameraKeyboardMoveInput;
  46975. }());
  46976. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  46977. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  46978. })(BABYLON || (BABYLON = {}));
  46979. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  46980. var BABYLON;
  46981. (function (BABYLON) {
  46982. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  46983. function ArcRotateCameraMouseWheelInput() {
  46984. this.wheelPrecision = 3.0;
  46985. /**
  46986. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  46987. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  46988. */
  46989. this.wheelDeltaPercentage = 0;
  46990. }
  46991. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  46992. var _this = this;
  46993. this._wheel = function (p, s) {
  46994. //sanity check - this should be a PointerWheel event.
  46995. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  46996. return;
  46997. var event = p.event;
  46998. var delta = 0;
  46999. if (event.wheelDelta) {
  47000. if (_this.wheelDeltaPercentage) {
  47001. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47002. if (event.wheelDelta > 0) {
  47003. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47004. }
  47005. else {
  47006. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47007. }
  47008. }
  47009. else {
  47010. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47011. }
  47012. }
  47013. else if (event.detail) {
  47014. delta = -event.detail / _this.wheelPrecision;
  47015. }
  47016. if (delta)
  47017. _this.camera.inertialRadiusOffset += delta;
  47018. if (event.preventDefault) {
  47019. if (!noPreventDefault) {
  47020. event.preventDefault();
  47021. }
  47022. }
  47023. };
  47024. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47025. };
  47026. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47027. if (this._observer && element) {
  47028. this.camera.getScene().onPointerObservable.remove(this._observer);
  47029. this._observer = null;
  47030. this._wheel = null;
  47031. }
  47032. };
  47033. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47034. return "ArcRotateCameraMouseWheelInput";
  47035. };
  47036. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47037. return "mousewheel";
  47038. };
  47039. __decorate([
  47040. BABYLON.serialize()
  47041. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47042. __decorate([
  47043. BABYLON.serialize()
  47044. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47045. return ArcRotateCameraMouseWheelInput;
  47046. }());
  47047. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47048. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47049. })(BABYLON || (BABYLON = {}));
  47050. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47051. var BABYLON;
  47052. (function (BABYLON) {
  47053. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47054. function ArcRotateCameraPointersInput() {
  47055. this.buttons = [0, 1, 2];
  47056. this.angularSensibilityX = 1000.0;
  47057. this.angularSensibilityY = 1000.0;
  47058. this.pinchPrecision = 12.0;
  47059. /**
  47060. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47061. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47062. */
  47063. this.pinchDeltaPercentage = 0;
  47064. this.panningSensibility = 1000.0;
  47065. this.multiTouchPanning = true;
  47066. this.multiTouchPanAndZoom = true;
  47067. this._isPanClick = false;
  47068. this.pinchInwards = true;
  47069. }
  47070. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47071. var _this = this;
  47072. var engine = this.camera.getEngine();
  47073. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47074. var pointA = null;
  47075. var pointB = null;
  47076. var previousPinchSquaredDistance = 0;
  47077. var initialDistance = 0;
  47078. var twoFingerActivityCount = 0;
  47079. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47080. this._pointerInput = function (p, s) {
  47081. var evt = p.event;
  47082. var isTouch = p.event.pointerType === "touch";
  47083. if (engine.isInVRExclusivePointerMode) {
  47084. return;
  47085. }
  47086. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47087. return;
  47088. }
  47089. var srcElement = (evt.srcElement || evt.target);
  47090. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47091. try {
  47092. srcElement.setPointerCapture(evt.pointerId);
  47093. }
  47094. catch (e) {
  47095. //Nothing to do with the error. Execution will continue.
  47096. }
  47097. // Manage panning with pan button click
  47098. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47099. // manage pointers
  47100. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47101. if (pointA === null) {
  47102. pointA = cacheSoloPointer;
  47103. }
  47104. else if (pointB === null) {
  47105. pointB = cacheSoloPointer;
  47106. }
  47107. if (!noPreventDefault) {
  47108. evt.preventDefault();
  47109. element.focus();
  47110. }
  47111. }
  47112. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47113. _this.camera.restoreState();
  47114. }
  47115. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47116. try {
  47117. srcElement.releasePointerCapture(evt.pointerId);
  47118. }
  47119. catch (e) {
  47120. //Nothing to do with the error.
  47121. }
  47122. cacheSoloPointer = null;
  47123. previousPinchSquaredDistance = 0;
  47124. previousMultiTouchPanPosition.isPaning = false;
  47125. previousMultiTouchPanPosition.isPinching = false;
  47126. twoFingerActivityCount = 0;
  47127. initialDistance = 0;
  47128. if (!isTouch) {
  47129. pointB = null; // Mouse and pen are mono pointer
  47130. }
  47131. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47132. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47133. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47134. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47135. if (engine._badOS) {
  47136. pointA = pointB = null;
  47137. }
  47138. else {
  47139. //only remove the impacted pointer in case of multitouch allowing on most
  47140. //platforms switching from rotate to zoom and pan seamlessly.
  47141. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47142. pointA = pointB;
  47143. pointB = null;
  47144. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47145. }
  47146. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47147. pointB = null;
  47148. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47149. }
  47150. else {
  47151. pointA = pointB = null;
  47152. }
  47153. }
  47154. if (!noPreventDefault) {
  47155. evt.preventDefault();
  47156. }
  47157. }
  47158. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47159. if (!noPreventDefault) {
  47160. evt.preventDefault();
  47161. }
  47162. // One button down
  47163. if (pointA && pointB === null && cacheSoloPointer) {
  47164. if (_this.panningSensibility !== 0 &&
  47165. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47166. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47167. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47168. }
  47169. else {
  47170. var offsetX = evt.clientX - cacheSoloPointer.x;
  47171. var offsetY = evt.clientY - cacheSoloPointer.y;
  47172. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47173. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47174. }
  47175. cacheSoloPointer.x = evt.clientX;
  47176. cacheSoloPointer.y = evt.clientY;
  47177. }
  47178. // Two buttons down: pinch/pan
  47179. else if (pointA && pointB) {
  47180. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47181. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47182. ed.x = evt.clientX;
  47183. ed.y = evt.clientY;
  47184. var direction = _this.pinchInwards ? 1 : -1;
  47185. var distX = pointA.x - pointB.x;
  47186. var distY = pointA.y - pointB.y;
  47187. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47188. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47189. if (previousPinchSquaredDistance === 0) {
  47190. initialDistance = pinchDistance;
  47191. previousPinchSquaredDistance = pinchSquaredDistance;
  47192. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47193. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47194. return;
  47195. }
  47196. if (_this.multiTouchPanAndZoom) {
  47197. if (_this.pinchDeltaPercentage) {
  47198. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47199. }
  47200. else {
  47201. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47202. (_this.pinchPrecision *
  47203. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47204. direction);
  47205. }
  47206. if (_this.panningSensibility !== 0) {
  47207. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47208. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47209. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47210. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47211. previousMultiTouchPanPosition.x = pointersCenterX;
  47212. previousMultiTouchPanPosition.y = pointersCenterY;
  47213. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47214. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47215. }
  47216. }
  47217. else {
  47218. twoFingerActivityCount++;
  47219. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47220. if (_this.pinchDeltaPercentage) {
  47221. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47222. }
  47223. else {
  47224. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47225. (_this.pinchPrecision *
  47226. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47227. direction);
  47228. }
  47229. previousMultiTouchPanPosition.isPaning = false;
  47230. previousMultiTouchPanPosition.isPinching = true;
  47231. }
  47232. else {
  47233. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47234. if (!previousMultiTouchPanPosition.isPaning) {
  47235. previousMultiTouchPanPosition.isPaning = true;
  47236. previousMultiTouchPanPosition.isPinching = false;
  47237. previousMultiTouchPanPosition.x = ed.x;
  47238. previousMultiTouchPanPosition.y = ed.y;
  47239. return;
  47240. }
  47241. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47242. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47243. }
  47244. }
  47245. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47246. previousMultiTouchPanPosition.x = ed.x;
  47247. previousMultiTouchPanPosition.y = ed.y;
  47248. }
  47249. }
  47250. previousPinchSquaredDistance = pinchSquaredDistance;
  47251. }
  47252. }
  47253. };
  47254. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47255. this._onContextMenu = function (evt) {
  47256. evt.preventDefault();
  47257. };
  47258. if (!this.camera._useCtrlForPanning) {
  47259. element.addEventListener("contextmenu", this._onContextMenu, false);
  47260. }
  47261. this._onLostFocus = function () {
  47262. //this._keys = [];
  47263. pointA = pointB = null;
  47264. previousPinchSquaredDistance = 0;
  47265. previousMultiTouchPanPosition.isPaning = false;
  47266. previousMultiTouchPanPosition.isPinching = false;
  47267. twoFingerActivityCount = 0;
  47268. cacheSoloPointer = null;
  47269. initialDistance = 0;
  47270. };
  47271. this._onMouseMove = function (evt) {
  47272. if (!engine.isPointerLock) {
  47273. return;
  47274. }
  47275. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47276. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47277. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47278. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47279. if (!noPreventDefault) {
  47280. evt.preventDefault();
  47281. }
  47282. };
  47283. this._onGestureStart = function (e) {
  47284. if (window.MSGesture === undefined) {
  47285. return;
  47286. }
  47287. if (!_this._MSGestureHandler) {
  47288. _this._MSGestureHandler = new MSGesture();
  47289. _this._MSGestureHandler.target = element;
  47290. }
  47291. _this._MSGestureHandler.addPointer(e.pointerId);
  47292. };
  47293. this._onGesture = function (e) {
  47294. _this.camera.radius *= e.scale;
  47295. if (e.preventDefault) {
  47296. if (!noPreventDefault) {
  47297. e.stopPropagation();
  47298. e.preventDefault();
  47299. }
  47300. }
  47301. };
  47302. element.addEventListener("mousemove", this._onMouseMove, false);
  47303. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47304. element.addEventListener("MSGestureChange", this._onGesture, false);
  47305. BABYLON.Tools.RegisterTopRootEvents([
  47306. { name: "blur", handler: this._onLostFocus }
  47307. ]);
  47308. };
  47309. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47310. if (this._onLostFocus) {
  47311. BABYLON.Tools.UnregisterTopRootEvents([
  47312. { name: "blur", handler: this._onLostFocus }
  47313. ]);
  47314. }
  47315. if (element && this._observer) {
  47316. this.camera.getScene().onPointerObservable.remove(this._observer);
  47317. this._observer = null;
  47318. if (this._onContextMenu) {
  47319. element.removeEventListener("contextmenu", this._onContextMenu);
  47320. }
  47321. if (this._onMouseMove) {
  47322. element.removeEventListener("mousemove", this._onMouseMove);
  47323. }
  47324. if (this._onGestureStart) {
  47325. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47326. }
  47327. if (this._onGesture) {
  47328. element.removeEventListener("MSGestureChange", this._onGesture);
  47329. }
  47330. this._isPanClick = false;
  47331. this.pinchInwards = true;
  47332. this._onMouseMove = null;
  47333. this._onGestureStart = null;
  47334. this._onGesture = null;
  47335. this._MSGestureHandler = null;
  47336. this._onLostFocus = null;
  47337. this._onContextMenu = null;
  47338. }
  47339. };
  47340. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47341. return "ArcRotateCameraPointersInput";
  47342. };
  47343. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47344. return "pointers";
  47345. };
  47346. __decorate([
  47347. BABYLON.serialize()
  47348. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47349. __decorate([
  47350. BABYLON.serialize()
  47351. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47352. __decorate([
  47353. BABYLON.serialize()
  47354. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47355. __decorate([
  47356. BABYLON.serialize()
  47357. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47358. __decorate([
  47359. BABYLON.serialize()
  47360. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47361. __decorate([
  47362. BABYLON.serialize()
  47363. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47364. __decorate([
  47365. BABYLON.serialize()
  47366. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47367. __decorate([
  47368. BABYLON.serialize()
  47369. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47370. return ArcRotateCameraPointersInput;
  47371. }());
  47372. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47373. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47374. })(BABYLON || (BABYLON = {}));
  47375. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47376. var BABYLON;
  47377. (function (BABYLON) {
  47378. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47379. __extends(ArcRotateCameraInputsManager, _super);
  47380. function ArcRotateCameraInputsManager(camera) {
  47381. return _super.call(this, camera) || this;
  47382. }
  47383. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47384. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47385. return this;
  47386. };
  47387. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47388. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47389. return this;
  47390. };
  47391. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47392. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47393. return this;
  47394. };
  47395. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47396. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47397. return this;
  47398. };
  47399. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47400. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47401. return this;
  47402. };
  47403. return ArcRotateCameraInputsManager;
  47404. }(BABYLON.CameraInputsManager));
  47405. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47406. })(BABYLON || (BABYLON = {}));
  47407. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47408. var BABYLON;
  47409. (function (BABYLON) {
  47410. var ArcRotateCamera = /** @class */ (function (_super) {
  47411. __extends(ArcRotateCamera, _super);
  47412. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47413. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47414. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47415. _this.inertialAlphaOffset = 0;
  47416. _this.inertialBetaOffset = 0;
  47417. _this.inertialRadiusOffset = 0;
  47418. _this.lowerAlphaLimit = null;
  47419. _this.upperAlphaLimit = null;
  47420. _this.lowerBetaLimit = 0.01;
  47421. _this.upperBetaLimit = Math.PI;
  47422. _this.lowerRadiusLimit = null;
  47423. _this.upperRadiusLimit = null;
  47424. _this.inertialPanningX = 0;
  47425. _this.inertialPanningY = 0;
  47426. _this.pinchToPanMaxDistance = 20;
  47427. _this.panningDistanceLimit = null;
  47428. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47429. _this.panningInertia = 0.9;
  47430. //-- end properties for backward compatibility for inputs
  47431. _this.zoomOnFactor = 1;
  47432. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47433. _this.allowUpsideDown = true;
  47434. _this._viewMatrix = new BABYLON.Matrix();
  47435. // Panning
  47436. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47437. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47438. _this.checkCollisions = false;
  47439. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47440. _this._previousPosition = BABYLON.Vector3.Zero();
  47441. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47442. _this._newPosition = BABYLON.Vector3.Zero();
  47443. _this._computationVector = BABYLON.Vector3.Zero();
  47444. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47445. if (collidedMesh === void 0) { collidedMesh = null; }
  47446. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47447. newPosition.multiplyInPlace(_this._collider._radius);
  47448. }
  47449. if (!collidedMesh) {
  47450. _this._previousPosition.copyFrom(_this.position);
  47451. }
  47452. else {
  47453. _this.setPosition(newPosition);
  47454. if (_this.onCollide) {
  47455. _this.onCollide(collidedMesh);
  47456. }
  47457. }
  47458. // Recompute because of constraints
  47459. var cosa = Math.cos(_this.alpha);
  47460. var sina = Math.sin(_this.alpha);
  47461. var cosb = Math.cos(_this.beta);
  47462. var sinb = Math.sin(_this.beta);
  47463. if (sinb === 0) {
  47464. sinb = 0.0001;
  47465. }
  47466. var target = _this._getTargetPosition();
  47467. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47468. target.addToRef(_this._computationVector, _this._newPosition);
  47469. _this.position.copyFrom(_this._newPosition);
  47470. var up = _this.upVector;
  47471. if (_this.allowUpsideDown && _this.beta < 0) {
  47472. up = up.clone();
  47473. up = up.negate();
  47474. }
  47475. _this._computeViewMatrix(_this.position, target, up);
  47476. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47477. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47478. _this._collisionTriggered = false;
  47479. };
  47480. _this._target = BABYLON.Vector3.Zero();
  47481. if (target) {
  47482. _this.setTarget(target);
  47483. }
  47484. _this.alpha = alpha;
  47485. _this.beta = beta;
  47486. _this.radius = radius;
  47487. _this.getViewMatrix();
  47488. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47489. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47490. return _this;
  47491. }
  47492. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47493. get: function () {
  47494. return this._target;
  47495. },
  47496. set: function (value) {
  47497. this.setTarget(value);
  47498. },
  47499. enumerable: true,
  47500. configurable: true
  47501. });
  47502. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47503. //-- begin properties for backward compatibility for inputs
  47504. get: function () {
  47505. var pointers = this.inputs.attached["pointers"];
  47506. if (pointers)
  47507. return pointers.angularSensibilityX;
  47508. return 0;
  47509. },
  47510. set: function (value) {
  47511. var pointers = this.inputs.attached["pointers"];
  47512. if (pointers) {
  47513. pointers.angularSensibilityX = value;
  47514. }
  47515. },
  47516. enumerable: true,
  47517. configurable: true
  47518. });
  47519. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47520. get: function () {
  47521. var pointers = this.inputs.attached["pointers"];
  47522. if (pointers)
  47523. return pointers.angularSensibilityY;
  47524. return 0;
  47525. },
  47526. set: function (value) {
  47527. var pointers = this.inputs.attached["pointers"];
  47528. if (pointers) {
  47529. pointers.angularSensibilityY = value;
  47530. }
  47531. },
  47532. enumerable: true,
  47533. configurable: true
  47534. });
  47535. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47536. get: function () {
  47537. var pointers = this.inputs.attached["pointers"];
  47538. if (pointers)
  47539. return pointers.pinchPrecision;
  47540. return 0;
  47541. },
  47542. set: function (value) {
  47543. var pointers = this.inputs.attached["pointers"];
  47544. if (pointers) {
  47545. pointers.pinchPrecision = value;
  47546. }
  47547. },
  47548. enumerable: true,
  47549. configurable: true
  47550. });
  47551. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47552. get: function () {
  47553. var pointers = this.inputs.attached["pointers"];
  47554. if (pointers)
  47555. return pointers.pinchDeltaPercentage;
  47556. return 0;
  47557. },
  47558. set: function (value) {
  47559. var pointers = this.inputs.attached["pointers"];
  47560. if (pointers) {
  47561. pointers.pinchDeltaPercentage = value;
  47562. }
  47563. },
  47564. enumerable: true,
  47565. configurable: true
  47566. });
  47567. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47568. get: function () {
  47569. var pointers = this.inputs.attached["pointers"];
  47570. if (pointers)
  47571. return pointers.panningSensibility;
  47572. return 0;
  47573. },
  47574. set: function (value) {
  47575. var pointers = this.inputs.attached["pointers"];
  47576. if (pointers) {
  47577. pointers.panningSensibility = value;
  47578. }
  47579. },
  47580. enumerable: true,
  47581. configurable: true
  47582. });
  47583. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47584. get: function () {
  47585. var keyboard = this.inputs.attached["keyboard"];
  47586. if (keyboard)
  47587. return keyboard.keysUp;
  47588. return [];
  47589. },
  47590. set: function (value) {
  47591. var keyboard = this.inputs.attached["keyboard"];
  47592. if (keyboard)
  47593. keyboard.keysUp = value;
  47594. },
  47595. enumerable: true,
  47596. configurable: true
  47597. });
  47598. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47599. get: function () {
  47600. var keyboard = this.inputs.attached["keyboard"];
  47601. if (keyboard)
  47602. return keyboard.keysDown;
  47603. return [];
  47604. },
  47605. set: function (value) {
  47606. var keyboard = this.inputs.attached["keyboard"];
  47607. if (keyboard)
  47608. keyboard.keysDown = value;
  47609. },
  47610. enumerable: true,
  47611. configurable: true
  47612. });
  47613. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47614. get: function () {
  47615. var keyboard = this.inputs.attached["keyboard"];
  47616. if (keyboard)
  47617. return keyboard.keysLeft;
  47618. return [];
  47619. },
  47620. set: function (value) {
  47621. var keyboard = this.inputs.attached["keyboard"];
  47622. if (keyboard)
  47623. keyboard.keysLeft = value;
  47624. },
  47625. enumerable: true,
  47626. configurable: true
  47627. });
  47628. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47629. get: function () {
  47630. var keyboard = this.inputs.attached["keyboard"];
  47631. if (keyboard)
  47632. return keyboard.keysRight;
  47633. return [];
  47634. },
  47635. set: function (value) {
  47636. var keyboard = this.inputs.attached["keyboard"];
  47637. if (keyboard)
  47638. keyboard.keysRight = value;
  47639. },
  47640. enumerable: true,
  47641. configurable: true
  47642. });
  47643. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47644. get: function () {
  47645. var mousewheel = this.inputs.attached["mousewheel"];
  47646. if (mousewheel)
  47647. return mousewheel.wheelPrecision;
  47648. return 0;
  47649. },
  47650. set: function (value) {
  47651. var mousewheel = this.inputs.attached["mousewheel"];
  47652. if (mousewheel)
  47653. mousewheel.wheelPrecision = value;
  47654. },
  47655. enumerable: true,
  47656. configurable: true
  47657. });
  47658. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47659. get: function () {
  47660. var mousewheel = this.inputs.attached["mousewheel"];
  47661. if (mousewheel)
  47662. return mousewheel.wheelDeltaPercentage;
  47663. return 0;
  47664. },
  47665. set: function (value) {
  47666. var mousewheel = this.inputs.attached["mousewheel"];
  47667. if (mousewheel)
  47668. mousewheel.wheelDeltaPercentage = value;
  47669. },
  47670. enumerable: true,
  47671. configurable: true
  47672. });
  47673. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47674. get: function () {
  47675. return this._bouncingBehavior;
  47676. },
  47677. enumerable: true,
  47678. configurable: true
  47679. });
  47680. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47681. get: function () {
  47682. return this._bouncingBehavior != null;
  47683. },
  47684. set: function (value) {
  47685. if (value === this.useBouncingBehavior) {
  47686. return;
  47687. }
  47688. if (value) {
  47689. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47690. this.addBehavior(this._bouncingBehavior);
  47691. }
  47692. else if (this._bouncingBehavior) {
  47693. this.removeBehavior(this._bouncingBehavior);
  47694. this._bouncingBehavior = null;
  47695. }
  47696. },
  47697. enumerable: true,
  47698. configurable: true
  47699. });
  47700. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47701. get: function () {
  47702. return this._framingBehavior;
  47703. },
  47704. enumerable: true,
  47705. configurable: true
  47706. });
  47707. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47708. get: function () {
  47709. return this._framingBehavior != null;
  47710. },
  47711. set: function (value) {
  47712. if (value === this.useFramingBehavior) {
  47713. return;
  47714. }
  47715. if (value) {
  47716. this._framingBehavior = new BABYLON.FramingBehavior();
  47717. this.addBehavior(this._framingBehavior);
  47718. }
  47719. else if (this._framingBehavior) {
  47720. this.removeBehavior(this._framingBehavior);
  47721. this._framingBehavior = null;
  47722. }
  47723. },
  47724. enumerable: true,
  47725. configurable: true
  47726. });
  47727. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47728. get: function () {
  47729. return this._autoRotationBehavior;
  47730. },
  47731. enumerable: true,
  47732. configurable: true
  47733. });
  47734. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47735. get: function () {
  47736. return this._autoRotationBehavior != null;
  47737. },
  47738. set: function (value) {
  47739. if (value === this.useAutoRotationBehavior) {
  47740. return;
  47741. }
  47742. if (value) {
  47743. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47744. this.addBehavior(this._autoRotationBehavior);
  47745. }
  47746. else if (this._autoRotationBehavior) {
  47747. this.removeBehavior(this._autoRotationBehavior);
  47748. this._autoRotationBehavior = null;
  47749. }
  47750. },
  47751. enumerable: true,
  47752. configurable: true
  47753. });
  47754. // Cache
  47755. ArcRotateCamera.prototype._initCache = function () {
  47756. _super.prototype._initCache.call(this);
  47757. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47758. this._cache.alpha = undefined;
  47759. this._cache.beta = undefined;
  47760. this._cache.radius = undefined;
  47761. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47762. };
  47763. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47764. if (!ignoreParentClass) {
  47765. _super.prototype._updateCache.call(this);
  47766. }
  47767. this._cache._target.copyFrom(this._getTargetPosition());
  47768. this._cache.alpha = this.alpha;
  47769. this._cache.beta = this.beta;
  47770. this._cache.radius = this.radius;
  47771. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47772. };
  47773. ArcRotateCamera.prototype._getTargetPosition = function () {
  47774. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47775. var pos = this._targetHost.getAbsolutePosition();
  47776. if (this._targetBoundingCenter) {
  47777. pos.addToRef(this._targetBoundingCenter, this._target);
  47778. }
  47779. else {
  47780. this._target.copyFrom(pos);
  47781. }
  47782. }
  47783. var lockedTargetPosition = this._getLockedTargetPosition();
  47784. if (lockedTargetPosition) {
  47785. return lockedTargetPosition;
  47786. }
  47787. return this._target;
  47788. };
  47789. ArcRotateCamera.prototype.storeState = function () {
  47790. this._storedAlpha = this.alpha;
  47791. this._storedBeta = this.beta;
  47792. this._storedRadius = this.radius;
  47793. this._storedTarget = this._getTargetPosition().clone();
  47794. return _super.prototype.storeState.call(this);
  47795. };
  47796. /**
  47797. * Restored camera state. You must call storeState() first
  47798. */
  47799. ArcRotateCamera.prototype._restoreStateValues = function () {
  47800. if (!_super.prototype._restoreStateValues.call(this)) {
  47801. return false;
  47802. }
  47803. this.alpha = this._storedAlpha;
  47804. this.beta = this._storedBeta;
  47805. this.radius = this._storedRadius;
  47806. this.setTarget(this._storedTarget.clone());
  47807. this.inertialAlphaOffset = 0;
  47808. this.inertialBetaOffset = 0;
  47809. this.inertialRadiusOffset = 0;
  47810. this.inertialPanningX = 0;
  47811. this.inertialPanningY = 0;
  47812. return true;
  47813. };
  47814. // Synchronized
  47815. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47816. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47817. return false;
  47818. return this._cache._target.equals(this._getTargetPosition())
  47819. && this._cache.alpha === this.alpha
  47820. && this._cache.beta === this.beta
  47821. && this._cache.radius === this.radius
  47822. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47823. };
  47824. // Methods
  47825. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47826. var _this = this;
  47827. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47828. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47829. this._useCtrlForPanning = useCtrlForPanning;
  47830. this._panningMouseButton = panningMouseButton;
  47831. this.inputs.attachElement(element, noPreventDefault);
  47832. this._reset = function () {
  47833. _this.inertialAlphaOffset = 0;
  47834. _this.inertialBetaOffset = 0;
  47835. _this.inertialRadiusOffset = 0;
  47836. _this.inertialPanningX = 0;
  47837. _this.inertialPanningY = 0;
  47838. };
  47839. };
  47840. ArcRotateCamera.prototype.detachControl = function (element) {
  47841. this.inputs.detachElement(element);
  47842. if (this._reset) {
  47843. this._reset();
  47844. }
  47845. };
  47846. ArcRotateCamera.prototype._checkInputs = function () {
  47847. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47848. if (this._collisionTriggered) {
  47849. return;
  47850. }
  47851. this.inputs.checkInputs();
  47852. // Inertia
  47853. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47854. var inertialAlphaOffset = this.inertialAlphaOffset;
  47855. if (this.beta <= 0)
  47856. inertialAlphaOffset *= -1;
  47857. if (this.getScene().useRightHandedSystem)
  47858. inertialAlphaOffset *= -1;
  47859. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47860. inertialAlphaOffset *= -1;
  47861. this.alpha += inertialAlphaOffset;
  47862. this.beta += this.inertialBetaOffset;
  47863. this.radius -= this.inertialRadiusOffset;
  47864. this.inertialAlphaOffset *= this.inertia;
  47865. this.inertialBetaOffset *= this.inertia;
  47866. this.inertialRadiusOffset *= this.inertia;
  47867. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47868. this.inertialAlphaOffset = 0;
  47869. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47870. this.inertialBetaOffset = 0;
  47871. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47872. this.inertialRadiusOffset = 0;
  47873. }
  47874. // Panning inertia
  47875. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47876. if (!this._localDirection) {
  47877. this._localDirection = BABYLON.Vector3.Zero();
  47878. this._transformedDirection = BABYLON.Vector3.Zero();
  47879. }
  47880. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47881. this._localDirection.multiplyInPlace(this.panningAxis);
  47882. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47883. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47884. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47885. if (!this.panningAxis.y) {
  47886. this._transformedDirection.y = 0;
  47887. }
  47888. if (!this._targetHost) {
  47889. if (this.panningDistanceLimit) {
  47890. this._transformedDirection.addInPlace(this._target);
  47891. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47892. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47893. this._target.copyFrom(this._transformedDirection);
  47894. }
  47895. }
  47896. else {
  47897. this._target.addInPlace(this._transformedDirection);
  47898. }
  47899. }
  47900. this.inertialPanningX *= this.panningInertia;
  47901. this.inertialPanningY *= this.panningInertia;
  47902. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47903. this.inertialPanningX = 0;
  47904. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47905. this.inertialPanningY = 0;
  47906. }
  47907. // Limits
  47908. this._checkLimits();
  47909. _super.prototype._checkInputs.call(this);
  47910. };
  47911. ArcRotateCamera.prototype._checkLimits = function () {
  47912. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47913. if (this.allowUpsideDown && this.beta > Math.PI) {
  47914. this.beta = this.beta - (2 * Math.PI);
  47915. }
  47916. }
  47917. else {
  47918. if (this.beta < this.lowerBetaLimit) {
  47919. this.beta = this.lowerBetaLimit;
  47920. }
  47921. }
  47922. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47923. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47924. this.beta = this.beta + (2 * Math.PI);
  47925. }
  47926. }
  47927. else {
  47928. if (this.beta > this.upperBetaLimit) {
  47929. this.beta = this.upperBetaLimit;
  47930. }
  47931. }
  47932. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47933. this.alpha = this.lowerAlphaLimit;
  47934. }
  47935. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47936. this.alpha = this.upperAlphaLimit;
  47937. }
  47938. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47939. this.radius = this.lowerRadiusLimit;
  47940. }
  47941. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47942. this.radius = this.upperRadiusLimit;
  47943. }
  47944. };
  47945. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47946. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47947. this.radius = this._computationVector.length();
  47948. if (this.radius === 0) {
  47949. this.radius = 0.0001; // Just to avoid division by zero
  47950. }
  47951. // Alpha
  47952. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47953. if (this._computationVector.z < 0) {
  47954. this.alpha = 2 * Math.PI - this.alpha;
  47955. }
  47956. // Beta
  47957. this.beta = Math.acos(this._computationVector.y / this.radius);
  47958. this._checkLimits();
  47959. };
  47960. ArcRotateCamera.prototype.setPosition = function (position) {
  47961. if (this.position.equals(position)) {
  47962. return;
  47963. }
  47964. this.position.copyFrom(position);
  47965. this.rebuildAnglesAndRadius();
  47966. };
  47967. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  47968. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  47969. if (allowSamePosition === void 0) { allowSamePosition = false; }
  47970. if (target.getBoundingInfo) {
  47971. if (toBoundingCenter) {
  47972. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  47973. }
  47974. else {
  47975. this._targetBoundingCenter = null;
  47976. }
  47977. this._targetHost = target;
  47978. this._target = this._getTargetPosition();
  47979. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  47980. }
  47981. else {
  47982. var newTarget = target;
  47983. var currentTarget = this._getTargetPosition();
  47984. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  47985. return;
  47986. }
  47987. this._targetHost = null;
  47988. this._target = newTarget;
  47989. this._targetBoundingCenter = null;
  47990. this.onMeshTargetChangedObservable.notifyObservers(null);
  47991. }
  47992. this.rebuildAnglesAndRadius();
  47993. };
  47994. ArcRotateCamera.prototype._getViewMatrix = function () {
  47995. // Compute
  47996. var cosa = Math.cos(this.alpha);
  47997. var sina = Math.sin(this.alpha);
  47998. var cosb = Math.cos(this.beta);
  47999. var sinb = Math.sin(this.beta);
  48000. if (sinb === 0) {
  48001. sinb = 0.0001;
  48002. }
  48003. var target = this._getTargetPosition();
  48004. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48005. target.addToRef(this._computationVector, this._newPosition);
  48006. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48007. if (!this._collider) {
  48008. this._collider = new BABYLON.Collider();
  48009. }
  48010. this._collider._radius = this.collisionRadius;
  48011. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48012. this._collisionTriggered = true;
  48013. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48014. }
  48015. else {
  48016. this.position.copyFrom(this._newPosition);
  48017. var up = this.upVector;
  48018. if (this.allowUpsideDown && sinb < 0) {
  48019. up = up.clone();
  48020. up = up.negate();
  48021. }
  48022. this._computeViewMatrix(this.position, target, up);
  48023. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48024. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48025. }
  48026. this._currentTarget = target;
  48027. return this._viewMatrix;
  48028. };
  48029. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48030. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48031. meshes = meshes || this.getScene().meshes;
  48032. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48033. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48034. this.radius = distance * this.zoomOnFactor;
  48035. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48036. };
  48037. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48038. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48039. var meshesOrMinMaxVector;
  48040. var distance;
  48041. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48042. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48043. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48044. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48045. }
  48046. else { //minMaxVector and distance
  48047. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48048. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48049. distance = minMaxVectorAndDistance.distance;
  48050. }
  48051. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48052. if (!doNotUpdateMaxZ) {
  48053. this.maxZ = distance * 2;
  48054. }
  48055. };
  48056. /**
  48057. * @override
  48058. * Override Camera.createRigCamera
  48059. */
  48060. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48061. var alphaShift = 0;
  48062. switch (this.cameraRigMode) {
  48063. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48064. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48065. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48066. case BABYLON.Camera.RIG_MODE_VR:
  48067. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48068. break;
  48069. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48070. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48071. break;
  48072. }
  48073. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48074. rigCam._cameraRigParams = {};
  48075. return rigCam;
  48076. };
  48077. /**
  48078. * @override
  48079. * Override Camera._updateRigCameras
  48080. */
  48081. ArcRotateCamera.prototype._updateRigCameras = function () {
  48082. var camLeft = this._rigCameras[0];
  48083. var camRight = this._rigCameras[1];
  48084. camLeft.beta = camRight.beta = this.beta;
  48085. camLeft.radius = camRight.radius = this.radius;
  48086. switch (this.cameraRigMode) {
  48087. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48088. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48089. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48090. case BABYLON.Camera.RIG_MODE_VR:
  48091. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48092. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48093. break;
  48094. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48095. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48096. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48097. break;
  48098. }
  48099. _super.prototype._updateRigCameras.call(this);
  48100. };
  48101. ArcRotateCamera.prototype.dispose = function () {
  48102. this.inputs.clear();
  48103. _super.prototype.dispose.call(this);
  48104. };
  48105. ArcRotateCamera.prototype.getClassName = function () {
  48106. return "ArcRotateCamera";
  48107. };
  48108. __decorate([
  48109. BABYLON.serialize()
  48110. ], ArcRotateCamera.prototype, "alpha", void 0);
  48111. __decorate([
  48112. BABYLON.serialize()
  48113. ], ArcRotateCamera.prototype, "beta", void 0);
  48114. __decorate([
  48115. BABYLON.serialize()
  48116. ], ArcRotateCamera.prototype, "radius", void 0);
  48117. __decorate([
  48118. BABYLON.serializeAsVector3("target")
  48119. ], ArcRotateCamera.prototype, "_target", void 0);
  48120. __decorate([
  48121. BABYLON.serialize()
  48122. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48123. __decorate([
  48124. BABYLON.serialize()
  48125. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48126. __decorate([
  48127. BABYLON.serialize()
  48128. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48129. __decorate([
  48130. BABYLON.serialize()
  48131. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48132. __decorate([
  48133. BABYLON.serialize()
  48134. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48135. __decorate([
  48136. BABYLON.serialize()
  48137. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48138. __decorate([
  48139. BABYLON.serialize()
  48140. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48141. __decorate([
  48142. BABYLON.serialize()
  48143. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48144. __decorate([
  48145. BABYLON.serialize()
  48146. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48147. __decorate([
  48148. BABYLON.serialize()
  48149. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48150. __decorate([
  48151. BABYLON.serialize()
  48152. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48153. __decorate([
  48154. BABYLON.serialize()
  48155. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48156. __decorate([
  48157. BABYLON.serialize()
  48158. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48159. __decorate([
  48160. BABYLON.serializeAsVector3()
  48161. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48162. __decorate([
  48163. BABYLON.serialize()
  48164. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48165. __decorate([
  48166. BABYLON.serialize()
  48167. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48168. __decorate([
  48169. BABYLON.serialize()
  48170. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48171. return ArcRotateCamera;
  48172. }(BABYLON.TargetCamera));
  48173. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48174. })(BABYLON || (BABYLON = {}));
  48175. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48176. var BABYLON;
  48177. (function (BABYLON) {
  48178. /**
  48179. * The HemisphericLight simulates the ambient environment light,
  48180. * so the passed direction is the light reflection direction, not the incoming direction.
  48181. */
  48182. var HemisphericLight = /** @class */ (function (_super) {
  48183. __extends(HemisphericLight, _super);
  48184. /**
  48185. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48186. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48187. * The HemisphericLight can't cast shadows.
  48188. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48189. * @param name The friendly name of the light
  48190. * @param direction The direction of the light reflection
  48191. * @param scene The scene the light belongs to
  48192. */
  48193. function HemisphericLight(name, direction, scene) {
  48194. var _this = _super.call(this, name, scene) || this;
  48195. /**
  48196. * The groundColor is the light in the opposite direction to the one specified during creation.
  48197. * 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.
  48198. */
  48199. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48200. _this.direction = direction || BABYLON.Vector3.Up();
  48201. return _this;
  48202. }
  48203. HemisphericLight.prototype._buildUniformLayout = function () {
  48204. this._uniformBuffer.addUniform("vLightData", 4);
  48205. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48206. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48207. this._uniformBuffer.addUniform("vLightGround", 3);
  48208. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48209. this._uniformBuffer.addUniform("depthValues", 2);
  48210. this._uniformBuffer.create();
  48211. };
  48212. /**
  48213. * Returns the string "HemisphericLight".
  48214. * @return The class name
  48215. */
  48216. HemisphericLight.prototype.getClassName = function () {
  48217. return "HemisphericLight";
  48218. };
  48219. /**
  48220. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48221. * Returns the updated direction.
  48222. * @param target The target the direction should point to
  48223. * @return The computed direction
  48224. */
  48225. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48226. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48227. return this.direction;
  48228. };
  48229. /**
  48230. * Returns the shadow generator associated to the light.
  48231. * @returns Always null for hemispheric lights because it does not support shadows.
  48232. */
  48233. HemisphericLight.prototype.getShadowGenerator = function () {
  48234. return null;
  48235. };
  48236. /**
  48237. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48238. * @param effect The effect to update
  48239. * @param lightIndex The index of the light in the effect to update
  48240. * @returns The hemispheric light
  48241. */
  48242. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48243. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48244. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48245. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48246. return this;
  48247. };
  48248. /**
  48249. * @hidden internal use only.
  48250. */
  48251. HemisphericLight.prototype._getWorldMatrix = function () {
  48252. if (!this._worldMatrix) {
  48253. this._worldMatrix = BABYLON.Matrix.Identity();
  48254. }
  48255. return this._worldMatrix;
  48256. };
  48257. /**
  48258. * Returns the integer 3.
  48259. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48260. */
  48261. HemisphericLight.prototype.getTypeID = function () {
  48262. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48263. };
  48264. __decorate([
  48265. BABYLON.serializeAsColor3()
  48266. ], HemisphericLight.prototype, "groundColor", void 0);
  48267. __decorate([
  48268. BABYLON.serializeAsVector3()
  48269. ], HemisphericLight.prototype, "direction", void 0);
  48270. return HemisphericLight;
  48271. }(BABYLON.Light));
  48272. BABYLON.HemisphericLight = HemisphericLight;
  48273. })(BABYLON || (BABYLON = {}));
  48274. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48275. var BABYLON;
  48276. (function (BABYLON) {
  48277. /**
  48278. * Base implementation IShadowLight
  48279. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48280. */
  48281. var ShadowLight = /** @class */ (function (_super) {
  48282. __extends(ShadowLight, _super);
  48283. function ShadowLight() {
  48284. var _this = _super !== null && _super.apply(this, arguments) || this;
  48285. _this._needProjectionMatrixCompute = true;
  48286. return _this;
  48287. }
  48288. ShadowLight.prototype._setPosition = function (value) {
  48289. this._position = value;
  48290. };
  48291. Object.defineProperty(ShadowLight.prototype, "position", {
  48292. /**
  48293. * Sets the position the shadow will be casted from. Also use as the light position for both
  48294. * point and spot lights.
  48295. */
  48296. get: function () {
  48297. return this._position;
  48298. },
  48299. /**
  48300. * Sets the position the shadow will be casted from. Also use as the light position for both
  48301. * point and spot lights.
  48302. */
  48303. set: function (value) {
  48304. this._setPosition(value);
  48305. },
  48306. enumerable: true,
  48307. configurable: true
  48308. });
  48309. ShadowLight.prototype._setDirection = function (value) {
  48310. this._direction = value;
  48311. };
  48312. Object.defineProperty(ShadowLight.prototype, "direction", {
  48313. /**
  48314. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48315. * Also use as the light direction on spot and directional lights.
  48316. */
  48317. get: function () {
  48318. return this._direction;
  48319. },
  48320. /**
  48321. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48322. * Also use as the light direction on spot and directional lights.
  48323. */
  48324. set: function (value) {
  48325. this._setDirection(value);
  48326. },
  48327. enumerable: true,
  48328. configurable: true
  48329. });
  48330. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48331. /**
  48332. * Gets the shadow projection clipping minimum z value.
  48333. */
  48334. get: function () {
  48335. return this._shadowMinZ;
  48336. },
  48337. /**
  48338. * Sets the shadow projection clipping minimum z value.
  48339. */
  48340. set: function (value) {
  48341. this._shadowMinZ = value;
  48342. this.forceProjectionMatrixCompute();
  48343. },
  48344. enumerable: true,
  48345. configurable: true
  48346. });
  48347. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48348. /**
  48349. * Sets the shadow projection clipping maximum z value.
  48350. */
  48351. get: function () {
  48352. return this._shadowMaxZ;
  48353. },
  48354. /**
  48355. * Gets the shadow projection clipping maximum z value.
  48356. */
  48357. set: function (value) {
  48358. this._shadowMaxZ = value;
  48359. this.forceProjectionMatrixCompute();
  48360. },
  48361. enumerable: true,
  48362. configurable: true
  48363. });
  48364. /**
  48365. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48366. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48367. */
  48368. ShadowLight.prototype.computeTransformedInformation = function () {
  48369. if (this.parent && this.parent.getWorldMatrix) {
  48370. if (!this.transformedPosition) {
  48371. this.transformedPosition = BABYLON.Vector3.Zero();
  48372. }
  48373. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48374. // In case the direction is present.
  48375. if (this.direction) {
  48376. if (!this.transformedDirection) {
  48377. this.transformedDirection = BABYLON.Vector3.Zero();
  48378. }
  48379. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48380. }
  48381. return true;
  48382. }
  48383. return false;
  48384. };
  48385. /**
  48386. * Return the depth scale used for the shadow map.
  48387. * @returns the depth scale.
  48388. */
  48389. ShadowLight.prototype.getDepthScale = function () {
  48390. return 50.0;
  48391. };
  48392. /**
  48393. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48394. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48395. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48396. */
  48397. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48398. return this.transformedDirection ? this.transformedDirection : this.direction;
  48399. };
  48400. /**
  48401. * Returns the ShadowLight absolute position in the World.
  48402. * @returns the position vector in world space
  48403. */
  48404. ShadowLight.prototype.getAbsolutePosition = function () {
  48405. return this.transformedPosition ? this.transformedPosition : this.position;
  48406. };
  48407. /**
  48408. * Sets the ShadowLight direction toward the passed target.
  48409. * @param target The point tot target in local space
  48410. * @returns the updated ShadowLight direction
  48411. */
  48412. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48413. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48414. return this.direction;
  48415. };
  48416. /**
  48417. * Returns the light rotation in euler definition.
  48418. * @returns the x y z rotation in local space.
  48419. */
  48420. ShadowLight.prototype.getRotation = function () {
  48421. this.direction.normalize();
  48422. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48423. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48424. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48425. };
  48426. /**
  48427. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48428. * @returns true if a cube texture needs to be use
  48429. */
  48430. ShadowLight.prototype.needCube = function () {
  48431. return false;
  48432. };
  48433. /**
  48434. * Detects if the projection matrix requires to be recomputed this frame.
  48435. * @returns true if it requires to be recomputed otherwise, false.
  48436. */
  48437. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48438. return this._needProjectionMatrixCompute;
  48439. };
  48440. /**
  48441. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48442. */
  48443. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48444. this._needProjectionMatrixCompute = true;
  48445. };
  48446. /**
  48447. * Get the world matrix of the sahdow lights.
  48448. * @hidden Internal Use Only
  48449. */
  48450. ShadowLight.prototype._getWorldMatrix = function () {
  48451. if (!this._worldMatrix) {
  48452. this._worldMatrix = BABYLON.Matrix.Identity();
  48453. }
  48454. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48455. return this._worldMatrix;
  48456. };
  48457. /**
  48458. * Gets the minZ used for shadow according to both the scene and the light.
  48459. * @param activeCamera The camera we are returning the min for
  48460. * @returns the depth min z
  48461. */
  48462. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48463. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48464. };
  48465. /**
  48466. * Gets the maxZ used for shadow according to both the scene and the light.
  48467. * @param activeCamera The camera we are returning the max for
  48468. * @returns the depth max z
  48469. */
  48470. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48471. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48472. };
  48473. /**
  48474. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48475. * @param matrix The materix to updated with the projection information
  48476. * @param viewMatrix The transform matrix of the light
  48477. * @param renderList The list of mesh to render in the map
  48478. * @returns The current light
  48479. */
  48480. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48481. if (this.customProjectionMatrixBuilder) {
  48482. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48483. }
  48484. else {
  48485. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48486. }
  48487. return this;
  48488. };
  48489. __decorate([
  48490. BABYLON.serializeAsVector3()
  48491. ], ShadowLight.prototype, "position", null);
  48492. __decorate([
  48493. BABYLON.serializeAsVector3()
  48494. ], ShadowLight.prototype, "direction", null);
  48495. __decorate([
  48496. BABYLON.serialize()
  48497. ], ShadowLight.prototype, "shadowMinZ", null);
  48498. __decorate([
  48499. BABYLON.serialize()
  48500. ], ShadowLight.prototype, "shadowMaxZ", null);
  48501. return ShadowLight;
  48502. }(BABYLON.Light));
  48503. BABYLON.ShadowLight = ShadowLight;
  48504. })(BABYLON || (BABYLON = {}));
  48505. //# sourceMappingURL=babylon.shadowLight.js.map
  48506. var BABYLON;
  48507. (function (BABYLON) {
  48508. /**
  48509. * A point light is a light defined by an unique point in world space.
  48510. * The light is emitted in every direction from this point.
  48511. * A good example of a point light is a standard light bulb.
  48512. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48513. */
  48514. var PointLight = /** @class */ (function (_super) {
  48515. __extends(PointLight, _super);
  48516. /**
  48517. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48518. * A PointLight emits the light in every direction.
  48519. * It can cast shadows.
  48520. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48521. * ```javascript
  48522. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48523. * ```
  48524. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48525. * @param name The light friendly name
  48526. * @param position The position of the point light in the scene
  48527. * @param scene The scene the lights belongs to
  48528. */
  48529. function PointLight(name, position, scene) {
  48530. var _this = _super.call(this, name, scene) || this;
  48531. _this._shadowAngle = Math.PI / 2;
  48532. _this.position = position;
  48533. return _this;
  48534. }
  48535. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48536. /**
  48537. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48538. * This specifies what angle the shadow will use to be created.
  48539. *
  48540. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48541. */
  48542. get: function () {
  48543. return this._shadowAngle;
  48544. },
  48545. /**
  48546. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48547. * This specifies what angle the shadow will use to be created.
  48548. *
  48549. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48550. */
  48551. set: function (value) {
  48552. this._shadowAngle = value;
  48553. this.forceProjectionMatrixCompute();
  48554. },
  48555. enumerable: true,
  48556. configurable: true
  48557. });
  48558. Object.defineProperty(PointLight.prototype, "direction", {
  48559. /**
  48560. * Gets the direction if it has been set.
  48561. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48562. */
  48563. get: function () {
  48564. return this._direction;
  48565. },
  48566. /**
  48567. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48568. */
  48569. set: function (value) {
  48570. var previousNeedCube = this.needCube();
  48571. this._direction = value;
  48572. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48573. this._shadowGenerator.recreateShadowMap();
  48574. }
  48575. },
  48576. enumerable: true,
  48577. configurable: true
  48578. });
  48579. /**
  48580. * Returns the string "PointLight"
  48581. * @returns the class name
  48582. */
  48583. PointLight.prototype.getClassName = function () {
  48584. return "PointLight";
  48585. };
  48586. /**
  48587. * Returns the integer 0.
  48588. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48589. */
  48590. PointLight.prototype.getTypeID = function () {
  48591. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48592. };
  48593. /**
  48594. * Specifies wether or not the shadowmap should be a cube texture.
  48595. * @returns true if the shadowmap needs to be a cube texture.
  48596. */
  48597. PointLight.prototype.needCube = function () {
  48598. return !this.direction;
  48599. };
  48600. /**
  48601. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48602. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48603. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48604. */
  48605. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48606. if (this.direction) {
  48607. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48608. }
  48609. else {
  48610. switch (faceIndex) {
  48611. case 0:
  48612. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48613. case 1:
  48614. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48615. case 2:
  48616. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48617. case 3:
  48618. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48619. case 4:
  48620. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48621. case 5:
  48622. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48623. }
  48624. }
  48625. return BABYLON.Vector3.Zero();
  48626. };
  48627. /**
  48628. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48629. * - fov = PI / 2
  48630. * - aspect ratio : 1.0
  48631. * - z-near and far equal to the active camera minZ and maxZ.
  48632. * Returns the PointLight.
  48633. */
  48634. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48635. var activeCamera = this.getScene().activeCamera;
  48636. if (!activeCamera) {
  48637. return;
  48638. }
  48639. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48640. };
  48641. PointLight.prototype._buildUniformLayout = function () {
  48642. this._uniformBuffer.addUniform("vLightData", 4);
  48643. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48644. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48645. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48646. this._uniformBuffer.addUniform("depthValues", 2);
  48647. this._uniformBuffer.create();
  48648. };
  48649. /**
  48650. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48651. * @param effect The effect to update
  48652. * @param lightIndex The index of the light in the effect to update
  48653. * @returns The point light
  48654. */
  48655. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48656. if (this.computeTransformedInformation()) {
  48657. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48658. return this;
  48659. }
  48660. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48661. return this;
  48662. };
  48663. __decorate([
  48664. BABYLON.serialize()
  48665. ], PointLight.prototype, "shadowAngle", null);
  48666. return PointLight;
  48667. }(BABYLON.ShadowLight));
  48668. BABYLON.PointLight = PointLight;
  48669. })(BABYLON || (BABYLON = {}));
  48670. //# sourceMappingURL=babylon.pointLight.js.map
  48671. var BABYLON;
  48672. (function (BABYLON) {
  48673. /**
  48674. * A directional light is defined by a direction (what a surprise!).
  48675. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48676. * 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.
  48677. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48678. */
  48679. var DirectionalLight = /** @class */ (function (_super) {
  48680. __extends(DirectionalLight, _super);
  48681. /**
  48682. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48683. * The directional light is emitted from everywhere in the given direction.
  48684. * It can cast shawdows.
  48685. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48686. * @param name The friendly name of the light
  48687. * @param direction The direction of the light
  48688. * @param scene The scene the light belongs to
  48689. */
  48690. function DirectionalLight(name, direction, scene) {
  48691. var _this = _super.call(this, name, scene) || this;
  48692. _this._shadowFrustumSize = 0;
  48693. _this._shadowOrthoScale = 0.1;
  48694. /**
  48695. * Automatically compute the projection matrix to best fit (including all the casters)
  48696. * on each frame.
  48697. */
  48698. _this.autoUpdateExtends = true;
  48699. // Cache
  48700. _this._orthoLeft = Number.MAX_VALUE;
  48701. _this._orthoRight = Number.MIN_VALUE;
  48702. _this._orthoTop = Number.MIN_VALUE;
  48703. _this._orthoBottom = Number.MAX_VALUE;
  48704. _this.position = direction.scale(-1.0);
  48705. _this.direction = direction;
  48706. return _this;
  48707. }
  48708. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48709. /**
  48710. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48711. */
  48712. get: function () {
  48713. return this._shadowFrustumSize;
  48714. },
  48715. /**
  48716. * Specifies a fix frustum size for the shadow generation.
  48717. */
  48718. set: function (value) {
  48719. this._shadowFrustumSize = value;
  48720. this.forceProjectionMatrixCompute();
  48721. },
  48722. enumerable: true,
  48723. configurable: true
  48724. });
  48725. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48726. /**
  48727. * Gets the shadow projection scale against the optimal computed one.
  48728. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48729. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48730. */
  48731. get: function () {
  48732. return this._shadowOrthoScale;
  48733. },
  48734. /**
  48735. * Sets the shadow projection scale against the optimal computed one.
  48736. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48737. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48738. */
  48739. set: function (value) {
  48740. this._shadowOrthoScale = value;
  48741. this.forceProjectionMatrixCompute();
  48742. },
  48743. enumerable: true,
  48744. configurable: true
  48745. });
  48746. /**
  48747. * Returns the string "DirectionalLight".
  48748. * @return The class name
  48749. */
  48750. DirectionalLight.prototype.getClassName = function () {
  48751. return "DirectionalLight";
  48752. };
  48753. /**
  48754. * Returns the integer 1.
  48755. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48756. */
  48757. DirectionalLight.prototype.getTypeID = function () {
  48758. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48759. };
  48760. /**
  48761. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48762. * Returns the DirectionalLight Shadow projection matrix.
  48763. */
  48764. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48765. if (this.shadowFrustumSize > 0) {
  48766. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48767. }
  48768. else {
  48769. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48770. }
  48771. };
  48772. /**
  48773. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48774. * Returns the DirectionalLight Shadow projection matrix.
  48775. */
  48776. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48777. var activeCamera = this.getScene().activeCamera;
  48778. if (!activeCamera) {
  48779. return;
  48780. }
  48781. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48782. };
  48783. /**
  48784. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48785. * Returns the DirectionalLight Shadow projection matrix.
  48786. */
  48787. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48788. var activeCamera = this.getScene().activeCamera;
  48789. if (!activeCamera) {
  48790. return;
  48791. }
  48792. // Check extends
  48793. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48794. var tempVector3 = BABYLON.Vector3.Zero();
  48795. this._orthoLeft = Number.MAX_VALUE;
  48796. this._orthoRight = Number.MIN_VALUE;
  48797. this._orthoTop = Number.MIN_VALUE;
  48798. this._orthoBottom = Number.MAX_VALUE;
  48799. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48800. var mesh = renderList[meshIndex];
  48801. if (!mesh) {
  48802. continue;
  48803. }
  48804. var boundingInfo = mesh.getBoundingInfo();
  48805. var boundingBox = boundingInfo.boundingBox;
  48806. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48807. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48808. if (tempVector3.x < this._orthoLeft)
  48809. this._orthoLeft = tempVector3.x;
  48810. if (tempVector3.y < this._orthoBottom)
  48811. this._orthoBottom = tempVector3.y;
  48812. if (tempVector3.x > this._orthoRight)
  48813. this._orthoRight = tempVector3.x;
  48814. if (tempVector3.y > this._orthoTop)
  48815. this._orthoTop = tempVector3.y;
  48816. }
  48817. }
  48818. }
  48819. var xOffset = this._orthoRight - this._orthoLeft;
  48820. var yOffset = this._orthoTop - this._orthoBottom;
  48821. 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);
  48822. };
  48823. DirectionalLight.prototype._buildUniformLayout = function () {
  48824. this._uniformBuffer.addUniform("vLightData", 4);
  48825. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48826. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48827. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48828. this._uniformBuffer.addUniform("depthValues", 2);
  48829. this._uniformBuffer.create();
  48830. };
  48831. /**
  48832. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48833. * @param effect The effect to update
  48834. * @param lightIndex The index of the light in the effect to update
  48835. * @returns The directional light
  48836. */
  48837. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48838. if (this.computeTransformedInformation()) {
  48839. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48840. return this;
  48841. }
  48842. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48843. return this;
  48844. };
  48845. /**
  48846. * Gets the minZ used for shadow according to both the scene and the light.
  48847. *
  48848. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48849. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48850. * @param activeCamera The camera we are returning the min for
  48851. * @returns the depth min z
  48852. */
  48853. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48854. return 1;
  48855. };
  48856. /**
  48857. * Gets the maxZ used for shadow according to both the scene and the light.
  48858. *
  48859. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48860. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48861. * @param activeCamera The camera we are returning the max for
  48862. * @returns the depth max z
  48863. */
  48864. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48865. return 1;
  48866. };
  48867. __decorate([
  48868. BABYLON.serialize()
  48869. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48870. __decorate([
  48871. BABYLON.serialize()
  48872. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48873. __decorate([
  48874. BABYLON.serialize()
  48875. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48876. return DirectionalLight;
  48877. }(BABYLON.ShadowLight));
  48878. BABYLON.DirectionalLight = DirectionalLight;
  48879. })(BABYLON || (BABYLON = {}));
  48880. //# sourceMappingURL=babylon.directionalLight.js.map
  48881. var BABYLON;
  48882. (function (BABYLON) {
  48883. /**
  48884. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48885. * These values define a cone of light starting from the position, emitting toward the direction.
  48886. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48887. * and the exponent defines the speed of the decay of the light with distance (reach).
  48888. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48889. */
  48890. var SpotLight = /** @class */ (function (_super) {
  48891. __extends(SpotLight, _super);
  48892. /**
  48893. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48894. * It can cast shadows.
  48895. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48896. * @param name The light friendly name
  48897. * @param position The position of the spot light in the scene
  48898. * @param direction The direction of the light in the scene
  48899. * @param angle The cone angle of the light in Radians
  48900. * @param exponent The light decay speed with the distance from the emission spot
  48901. * @param scene The scene the lights belongs to
  48902. */
  48903. function SpotLight(name, position, direction, angle, exponent, scene) {
  48904. var _this = _super.call(this, name, scene) || this;
  48905. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48906. _this._projectionTextureLightNear = 1e-6;
  48907. _this._projectionTextureLightFar = 1000.0;
  48908. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48909. _this._projectionTextureViewLightDirty = true;
  48910. _this._projectionTextureProjectionLightDirty = true;
  48911. _this._projectionTextureDirty = true;
  48912. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48913. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48914. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48915. _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);
  48916. _this.position = position;
  48917. _this.direction = direction;
  48918. _this.angle = angle;
  48919. _this.exponent = exponent;
  48920. return _this;
  48921. }
  48922. Object.defineProperty(SpotLight.prototype, "angle", {
  48923. /**
  48924. * Gets the cone angle of the spot light in Radians.
  48925. */
  48926. get: function () {
  48927. return this._angle;
  48928. },
  48929. /**
  48930. * Sets the cone angle of the spot light in Radians.
  48931. */
  48932. set: function (value) {
  48933. this._angle = value;
  48934. this._projectionTextureProjectionLightDirty = true;
  48935. this.forceProjectionMatrixCompute();
  48936. },
  48937. enumerable: true,
  48938. configurable: true
  48939. });
  48940. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48941. /**
  48942. * Allows scaling the angle of the light for shadow generation only.
  48943. */
  48944. get: function () {
  48945. return this._shadowAngleScale;
  48946. },
  48947. /**
  48948. * Allows scaling the angle of the light for shadow generation only.
  48949. */
  48950. set: function (value) {
  48951. this._shadowAngleScale = value;
  48952. this.forceProjectionMatrixCompute();
  48953. },
  48954. enumerable: true,
  48955. configurable: true
  48956. });
  48957. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  48958. /**
  48959. * Allows reading the projecton texture
  48960. */
  48961. get: function () {
  48962. return this._projectionTextureMatrix;
  48963. },
  48964. enumerable: true,
  48965. configurable: true
  48966. });
  48967. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  48968. /**
  48969. * Gets the near clip of the Spotlight for texture projection.
  48970. */
  48971. get: function () {
  48972. return this._projectionTextureLightNear;
  48973. },
  48974. /**
  48975. * Sets the near clip of the Spotlight for texture projection.
  48976. */
  48977. set: function (value) {
  48978. this._projectionTextureLightNear = value;
  48979. this._projectionTextureProjectionLightDirty = true;
  48980. },
  48981. enumerable: true,
  48982. configurable: true
  48983. });
  48984. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  48985. /**
  48986. * Gets the far clip of the Spotlight for texture projection.
  48987. */
  48988. get: function () {
  48989. return this._projectionTextureLightFar;
  48990. },
  48991. /**
  48992. * Sets the far clip of the Spotlight for texture projection.
  48993. */
  48994. set: function (value) {
  48995. this._projectionTextureLightFar = value;
  48996. this._projectionTextureProjectionLightDirty = true;
  48997. },
  48998. enumerable: true,
  48999. configurable: true
  49000. });
  49001. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49002. /**
  49003. * Gets the Up vector of the Spotlight for texture projection.
  49004. */
  49005. get: function () {
  49006. return this._projectionTextureUpDirection;
  49007. },
  49008. /**
  49009. * Sets the Up vector of the Spotlight for texture projection.
  49010. */
  49011. set: function (value) {
  49012. this._projectionTextureUpDirection = value;
  49013. this._projectionTextureProjectionLightDirty = true;
  49014. },
  49015. enumerable: true,
  49016. configurable: true
  49017. });
  49018. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49019. /**
  49020. * Gets the projection texture of the light.
  49021. */
  49022. get: function () {
  49023. return this._projectionTexture;
  49024. },
  49025. /**
  49026. * Sets the projection texture of the light.
  49027. */
  49028. set: function (value) {
  49029. this._projectionTexture = value;
  49030. this._projectionTextureDirty = true;
  49031. },
  49032. enumerable: true,
  49033. configurable: true
  49034. });
  49035. /**
  49036. * Returns the string "SpotLight".
  49037. * @returns the class name
  49038. */
  49039. SpotLight.prototype.getClassName = function () {
  49040. return "SpotLight";
  49041. };
  49042. /**
  49043. * Returns the integer 2.
  49044. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49045. */
  49046. SpotLight.prototype.getTypeID = function () {
  49047. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49048. };
  49049. /**
  49050. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49051. */
  49052. SpotLight.prototype._setDirection = function (value) {
  49053. _super.prototype._setDirection.call(this, value);
  49054. this._projectionTextureViewLightDirty = true;
  49055. };
  49056. /**
  49057. * Overrides the position setter to recompute the projection texture view light Matrix.
  49058. */
  49059. SpotLight.prototype._setPosition = function (value) {
  49060. _super.prototype._setPosition.call(this, value);
  49061. this._projectionTextureViewLightDirty = true;
  49062. };
  49063. /**
  49064. * 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.
  49065. * Returns the SpotLight.
  49066. */
  49067. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49068. var activeCamera = this.getScene().activeCamera;
  49069. if (!activeCamera) {
  49070. return;
  49071. }
  49072. this._shadowAngleScale = this._shadowAngleScale || 1;
  49073. var angle = this._shadowAngleScale * this._angle;
  49074. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49075. };
  49076. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49077. this._projectionTextureViewLightDirty = false;
  49078. this._projectionTextureDirty = true;
  49079. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49080. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49081. };
  49082. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49083. this._projectionTextureProjectionLightDirty = false;
  49084. this._projectionTextureDirty = true;
  49085. var light_far = this.projectionTextureLightFar;
  49086. var light_near = this.projectionTextureLightNear;
  49087. var P = light_far / (light_far - light_near);
  49088. var Q = -P * light_near;
  49089. var S = 1.0 / Math.tan(this._angle / 2.0);
  49090. var A = 1.0;
  49091. 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);
  49092. };
  49093. /**
  49094. * Main function for light texture projection matrix computing.
  49095. */
  49096. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49097. this._projectionTextureDirty = false;
  49098. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49099. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49100. };
  49101. SpotLight.prototype._buildUniformLayout = function () {
  49102. this._uniformBuffer.addUniform("vLightData", 4);
  49103. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49104. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49105. this._uniformBuffer.addUniform("vLightDirection", 3);
  49106. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49107. this._uniformBuffer.addUniform("depthValues", 2);
  49108. this._uniformBuffer.create();
  49109. };
  49110. /**
  49111. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49112. * @param effect The effect to update
  49113. * @param lightIndex The index of the light in the effect to update
  49114. * @returns The spot light
  49115. */
  49116. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49117. var normalizeDirection;
  49118. if (this.computeTransformedInformation()) {
  49119. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49120. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49121. }
  49122. else {
  49123. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49124. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49125. }
  49126. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49127. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49128. if (this._projectionTextureViewLightDirty) {
  49129. this._computeProjectionTextureViewLightMatrix();
  49130. }
  49131. if (this._projectionTextureProjectionLightDirty) {
  49132. this._computeProjectionTextureProjectionLightMatrix();
  49133. }
  49134. if (this._projectionTextureDirty) {
  49135. this._computeProjectionTextureMatrix();
  49136. }
  49137. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49138. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49139. }
  49140. return this;
  49141. };
  49142. /**
  49143. * Disposes the light and the associated resources.
  49144. */
  49145. SpotLight.prototype.dispose = function () {
  49146. _super.prototype.dispose.call(this);
  49147. if (this._projectionTexture) {
  49148. this._projectionTexture.dispose();
  49149. }
  49150. };
  49151. __decorate([
  49152. BABYLON.serialize()
  49153. ], SpotLight.prototype, "angle", null);
  49154. __decorate([
  49155. BABYLON.serialize()
  49156. ], SpotLight.prototype, "shadowAngleScale", null);
  49157. __decorate([
  49158. BABYLON.serialize()
  49159. ], SpotLight.prototype, "exponent", void 0);
  49160. __decorate([
  49161. BABYLON.serialize()
  49162. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49163. __decorate([
  49164. BABYLON.serialize()
  49165. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49166. __decorate([
  49167. BABYLON.serialize()
  49168. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49169. __decorate([
  49170. BABYLON.serializeAsTexture("projectedLightTexture")
  49171. ], SpotLight.prototype, "_projectionTexture", void 0);
  49172. return SpotLight;
  49173. }(BABYLON.ShadowLight));
  49174. BABYLON.SpotLight = SpotLight;
  49175. })(BABYLON || (BABYLON = {}));
  49176. //# sourceMappingURL=babylon.spotLight.js.map
  49177. var BABYLON;
  49178. (function (BABYLON) {
  49179. /**
  49180. * Class used to override all child animations of a given target
  49181. */
  49182. var AnimationPropertiesOverride = /** @class */ (function () {
  49183. function AnimationPropertiesOverride() {
  49184. /**
  49185. * Gets or sets a value indicating if animation blending must be used
  49186. */
  49187. this.enableBlending = false;
  49188. /**
  49189. * Gets or sets the blending speed to use when enableBlending is true
  49190. */
  49191. this.blendingSpeed = 0.01;
  49192. /**
  49193. * Gets or sets the default loop mode to use
  49194. */
  49195. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49196. }
  49197. return AnimationPropertiesOverride;
  49198. }());
  49199. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49200. })(BABYLON || (BABYLON = {}));
  49201. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49202. var BABYLON;
  49203. (function (BABYLON) {
  49204. /**
  49205. * Represents the range of an animation
  49206. */
  49207. var AnimationRange = /** @class */ (function () {
  49208. /**
  49209. * Initializes the range of an animation
  49210. * @param name The name of the animation range
  49211. * @param from The starting frame of the animation
  49212. * @param to The ending frame of the animation
  49213. */
  49214. function AnimationRange(
  49215. /**The name of the animation range**/
  49216. name,
  49217. /**The starting frame of the animation */
  49218. from,
  49219. /**The ending frame of the animation*/
  49220. to) {
  49221. this.name = name;
  49222. this.from = from;
  49223. this.to = to;
  49224. }
  49225. /**
  49226. * Makes a copy of the animation range
  49227. * @returns A copy of the animation range
  49228. */
  49229. AnimationRange.prototype.clone = function () {
  49230. return new AnimationRange(this.name, this.from, this.to);
  49231. };
  49232. return AnimationRange;
  49233. }());
  49234. BABYLON.AnimationRange = AnimationRange;
  49235. /**
  49236. * Composed of a frame, and an action function
  49237. */
  49238. var AnimationEvent = /** @class */ (function () {
  49239. /**
  49240. * Initializes the animation event
  49241. * @param frame The frame for which the event is triggered
  49242. * @param action The event to perform when triggered
  49243. * @param onlyOnce Specifies if the event should be triggered only once
  49244. */
  49245. function AnimationEvent(
  49246. /** The frame for which the event is triggered **/
  49247. frame,
  49248. /** The event to perform when triggered **/
  49249. action,
  49250. /** Specifies if the event should be triggered only once**/
  49251. onlyOnce) {
  49252. this.frame = frame;
  49253. this.action = action;
  49254. this.onlyOnce = onlyOnce;
  49255. /**
  49256. * Specifies if the animation event is done
  49257. */
  49258. this.isDone = false;
  49259. }
  49260. /** @hidden */
  49261. AnimationEvent.prototype._clone = function () {
  49262. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49263. };
  49264. return AnimationEvent;
  49265. }());
  49266. BABYLON.AnimationEvent = AnimationEvent;
  49267. /**
  49268. * A cursor which tracks a point on a path
  49269. */
  49270. var PathCursor = /** @class */ (function () {
  49271. /**
  49272. * Initializes the path cursor
  49273. * @param path The path to track
  49274. */
  49275. function PathCursor(path) {
  49276. this.path = path;
  49277. /**
  49278. * Stores path cursor callbacks for when an onchange event is triggered
  49279. */
  49280. this._onchange = new Array();
  49281. /**
  49282. * The value of the path cursor
  49283. */
  49284. this.value = 0;
  49285. /**
  49286. * The animation array of the path cursor
  49287. */
  49288. this.animations = new Array();
  49289. }
  49290. /**
  49291. * Gets the cursor point on the path
  49292. * @returns A point on the path cursor at the cursor location
  49293. */
  49294. PathCursor.prototype.getPoint = function () {
  49295. var point = this.path.getPointAtLengthPosition(this.value);
  49296. return new BABYLON.Vector3(point.x, 0, point.y);
  49297. };
  49298. /**
  49299. * Moves the cursor ahead by the step amount
  49300. * @param step The amount to move the cursor forward
  49301. * @returns This path cursor
  49302. */
  49303. PathCursor.prototype.moveAhead = function (step) {
  49304. if (step === void 0) { step = 0.002; }
  49305. this.move(step);
  49306. return this;
  49307. };
  49308. /**
  49309. * Moves the cursor behind by the step amount
  49310. * @param step The amount to move the cursor back
  49311. * @returns This path cursor
  49312. */
  49313. PathCursor.prototype.moveBack = function (step) {
  49314. if (step === void 0) { step = 0.002; }
  49315. this.move(-step);
  49316. return this;
  49317. };
  49318. /**
  49319. * Moves the cursor by the step amount
  49320. * If the step amount is greater than one, an exception is thrown
  49321. * @param step The amount to move the cursor
  49322. * @returns This path cursor
  49323. */
  49324. PathCursor.prototype.move = function (step) {
  49325. if (Math.abs(step) > 1) {
  49326. throw "step size should be less than 1.";
  49327. }
  49328. this.value += step;
  49329. this.ensureLimits();
  49330. this.raiseOnChange();
  49331. return this;
  49332. };
  49333. /**
  49334. * Ensures that the value is limited between zero and one
  49335. * @returns This path cursor
  49336. */
  49337. PathCursor.prototype.ensureLimits = function () {
  49338. while (this.value > 1) {
  49339. this.value -= 1;
  49340. }
  49341. while (this.value < 0) {
  49342. this.value += 1;
  49343. }
  49344. return this;
  49345. };
  49346. /**
  49347. * Runs onchange callbacks on change (used by the animation engine)
  49348. * @returns This path cursor
  49349. */
  49350. PathCursor.prototype.raiseOnChange = function () {
  49351. var _this = this;
  49352. this._onchange.forEach(function (f) { return f(_this); });
  49353. return this;
  49354. };
  49355. /**
  49356. * Executes a function on change
  49357. * @param f A path cursor onchange callback
  49358. * @returns This path cursor
  49359. */
  49360. PathCursor.prototype.onchange = function (f) {
  49361. this._onchange.push(f);
  49362. return this;
  49363. };
  49364. return PathCursor;
  49365. }());
  49366. BABYLON.PathCursor = PathCursor;
  49367. /**
  49368. * Enum for the animation key frame interpolation type
  49369. */
  49370. var AnimationKeyInterpolation;
  49371. (function (AnimationKeyInterpolation) {
  49372. /**
  49373. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49374. */
  49375. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49376. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49377. /**
  49378. * Class used to store any kind of animation
  49379. */
  49380. var Animation = /** @class */ (function () {
  49381. /**
  49382. * Initializes the animation
  49383. * @param name Name of the animation
  49384. * @param targetProperty Property to animate
  49385. * @param framePerSecond The frames per second of the animation
  49386. * @param dataType The data type of the animation
  49387. * @param loopMode The loop mode of the animation
  49388. * @param enableBlendings Specifies if blending should be enabled
  49389. */
  49390. function Animation(
  49391. /**Name of the animation */
  49392. name,
  49393. /**Property to animate */
  49394. targetProperty,
  49395. /**The frames per second of the animation */
  49396. framePerSecond,
  49397. /**The data type of the animation */
  49398. dataType,
  49399. /**The loop mode of the animation */
  49400. loopMode,
  49401. /**Specifies if blending should be enabled */
  49402. enableBlending) {
  49403. this.name = name;
  49404. this.targetProperty = targetProperty;
  49405. this.framePerSecond = framePerSecond;
  49406. this.dataType = dataType;
  49407. this.loopMode = loopMode;
  49408. this.enableBlending = enableBlending;
  49409. /**
  49410. * @hidden Internal use only
  49411. */
  49412. this._runtimeAnimations = new Array();
  49413. /**
  49414. * The set of event that will be linked to this animation
  49415. */
  49416. this._events = new Array();
  49417. /**
  49418. * Stores the blending speed of the animation
  49419. */
  49420. this.blendingSpeed = 0.01;
  49421. /**
  49422. * Stores the animation ranges for the animation
  49423. */
  49424. this._ranges = {};
  49425. this.targetPropertyPath = targetProperty.split(".");
  49426. this.dataType = dataType;
  49427. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49428. }
  49429. /**
  49430. * @hidden Internal use
  49431. */
  49432. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49433. var dataType = undefined;
  49434. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49435. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49436. }
  49437. else if (from instanceof BABYLON.Quaternion) {
  49438. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49439. }
  49440. else if (from instanceof BABYLON.Vector3) {
  49441. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49442. }
  49443. else if (from instanceof BABYLON.Vector2) {
  49444. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49445. }
  49446. else if (from instanceof BABYLON.Color3) {
  49447. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49448. }
  49449. else if (from instanceof BABYLON.Size) {
  49450. dataType = Animation.ANIMATIONTYPE_SIZE;
  49451. }
  49452. if (dataType == undefined) {
  49453. return null;
  49454. }
  49455. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49456. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49457. animation.setKeys(keys);
  49458. if (easingFunction !== undefined) {
  49459. animation.setEasingFunction(easingFunction);
  49460. }
  49461. return animation;
  49462. };
  49463. /**
  49464. * Sets up an animation
  49465. * @param property The property to animate
  49466. * @param animationType The animation type to apply
  49467. * @param framePerSecond The frames per second of the animation
  49468. * @param easingFunction The easing function used in the animation
  49469. * @returns The created animation
  49470. */
  49471. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49472. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49473. animation.setEasingFunction(easingFunction);
  49474. return animation;
  49475. };
  49476. /**
  49477. * Create and start an animation on a node
  49478. * @param name defines the name of the global animation that will be run on all nodes
  49479. * @param node defines the root node where the animation will take place
  49480. * @param targetProperty defines property to animate
  49481. * @param framePerSecond defines the number of frame per second yo use
  49482. * @param totalFrame defines the number of frames in total
  49483. * @param from defines the initial value
  49484. * @param to defines the final value
  49485. * @param loopMode defines which loop mode you want to use (off by default)
  49486. * @param easingFunction defines the easing function to use (linear by default)
  49487. * @param onAnimationEnd defines the callback to call when animation end
  49488. * @returns the animatable created for this animation
  49489. */
  49490. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49491. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49492. if (!animation) {
  49493. return null;
  49494. }
  49495. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49496. };
  49497. /**
  49498. * Create and start an animation on a node and its descendants
  49499. * @param name defines the name of the global animation that will be run on all nodes
  49500. * @param node defines the root node where the animation will take place
  49501. * @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
  49502. * @param targetProperty defines property to animate
  49503. * @param framePerSecond defines the number of frame per second to use
  49504. * @param totalFrame defines the number of frames in total
  49505. * @param from defines the initial value
  49506. * @param to defines the final value
  49507. * @param loopMode defines which loop mode you want to use (off by default)
  49508. * @param easingFunction defines the easing function to use (linear by default)
  49509. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49510. * @returns the list of animatables created for all nodes
  49511. * @example https://www.babylonjs-playground.com/#MH0VLI
  49512. */
  49513. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49514. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49515. if (!animation) {
  49516. return null;
  49517. }
  49518. var scene = node.getScene();
  49519. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49520. };
  49521. /**
  49522. * Creates a new animation, merges it with the existing animations and starts it
  49523. * @param name Name of the animation
  49524. * @param node Node which contains the scene that begins the animations
  49525. * @param targetProperty Specifies which property to animate
  49526. * @param framePerSecond The frames per second of the animation
  49527. * @param totalFrame The total number of frames
  49528. * @param from The frame at the beginning of the animation
  49529. * @param to The frame at the end of the animation
  49530. * @param loopMode Specifies the loop mode of the animation
  49531. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49532. * @param onAnimationEnd Callback to run once the animation is complete
  49533. * @returns Nullable animation
  49534. */
  49535. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49536. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49537. if (!animation) {
  49538. return null;
  49539. }
  49540. node.animations.push(animation);
  49541. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49542. };
  49543. /**
  49544. * Transition property of an host to the target Value
  49545. * @param property The property to transition
  49546. * @param targetValue The target Value of the property
  49547. * @param host The object where the property to animate belongs
  49548. * @param scene Scene used to run the animation
  49549. * @param frameRate Framerate (in frame/s) to use
  49550. * @param transition The transition type we want to use
  49551. * @param duration The duration of the animation, in milliseconds
  49552. * @param onAnimationEnd Callback trigger at the end of the animation
  49553. * @returns Nullable animation
  49554. */
  49555. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49556. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49557. if (duration <= 0) {
  49558. host[property] = targetValue;
  49559. if (onAnimationEnd) {
  49560. onAnimationEnd();
  49561. }
  49562. return null;
  49563. }
  49564. var endFrame = frameRate * (duration / 1000);
  49565. transition.setKeys([{
  49566. frame: 0,
  49567. value: host[property].clone ? host[property].clone() : host[property]
  49568. },
  49569. {
  49570. frame: endFrame,
  49571. value: targetValue
  49572. }]);
  49573. if (!host.animations) {
  49574. host.animations = [];
  49575. }
  49576. host.animations.push(transition);
  49577. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49578. animation.onAnimationEnd = onAnimationEnd;
  49579. return animation;
  49580. };
  49581. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49582. /**
  49583. * Return the array of runtime animations currently using this animation
  49584. */
  49585. get: function () {
  49586. return this._runtimeAnimations;
  49587. },
  49588. enumerable: true,
  49589. configurable: true
  49590. });
  49591. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49592. /**
  49593. * Specifies if any of the runtime animations are currently running
  49594. */
  49595. get: function () {
  49596. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49597. var runtimeAnimation = _a[_i];
  49598. if (!runtimeAnimation.isStopped) {
  49599. return true;
  49600. }
  49601. }
  49602. return false;
  49603. },
  49604. enumerable: true,
  49605. configurable: true
  49606. });
  49607. // Methods
  49608. /**
  49609. * Converts the animation to a string
  49610. * @param fullDetails support for multiple levels of logging within scene loading
  49611. * @returns String form of the animation
  49612. */
  49613. Animation.prototype.toString = function (fullDetails) {
  49614. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49615. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49616. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49617. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49618. if (fullDetails) {
  49619. ret += ", Ranges: {";
  49620. var first = true;
  49621. for (var name in this._ranges) {
  49622. if (first) {
  49623. ret += ", ";
  49624. first = false;
  49625. }
  49626. ret += name;
  49627. }
  49628. ret += "}";
  49629. }
  49630. return ret;
  49631. };
  49632. /**
  49633. * Add an event to this animation
  49634. * @param event Event to add
  49635. */
  49636. Animation.prototype.addEvent = function (event) {
  49637. this._events.push(event);
  49638. };
  49639. /**
  49640. * Remove all events found at the given frame
  49641. * @param frame The frame to remove events from
  49642. */
  49643. Animation.prototype.removeEvents = function (frame) {
  49644. for (var index = 0; index < this._events.length; index++) {
  49645. if (this._events[index].frame === frame) {
  49646. this._events.splice(index, 1);
  49647. index--;
  49648. }
  49649. }
  49650. };
  49651. /**
  49652. * Retrieves all the events from the animation
  49653. * @returns Events from the animation
  49654. */
  49655. Animation.prototype.getEvents = function () {
  49656. return this._events;
  49657. };
  49658. /**
  49659. * Creates an animation range
  49660. * @param name Name of the animation range
  49661. * @param from Starting frame of the animation range
  49662. * @param to Ending frame of the animation
  49663. */
  49664. Animation.prototype.createRange = function (name, from, to) {
  49665. // check name not already in use; could happen for bones after serialized
  49666. if (!this._ranges[name]) {
  49667. this._ranges[name] = new AnimationRange(name, from, to);
  49668. }
  49669. };
  49670. /**
  49671. * Deletes an animation range by name
  49672. * @param name Name of the animation range to delete
  49673. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49674. */
  49675. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49676. if (deleteFrames === void 0) { deleteFrames = true; }
  49677. var range = this._ranges[name];
  49678. if (!range) {
  49679. return;
  49680. }
  49681. if (deleteFrames) {
  49682. var from = range.from;
  49683. var to = range.to;
  49684. // this loop MUST go high to low for multiple splices to work
  49685. for (var key = this._keys.length - 1; key >= 0; key--) {
  49686. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49687. this._keys.splice(key, 1);
  49688. }
  49689. }
  49690. }
  49691. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49692. };
  49693. /**
  49694. * Gets the animation range by name, or null if not defined
  49695. * @param name Name of the animation range
  49696. * @returns Nullable animation range
  49697. */
  49698. Animation.prototype.getRange = function (name) {
  49699. return this._ranges[name];
  49700. };
  49701. /**
  49702. * Gets the key frames from the animation
  49703. * @returns The key frames of the animation
  49704. */
  49705. Animation.prototype.getKeys = function () {
  49706. return this._keys;
  49707. };
  49708. /**
  49709. * Gets the highest frame rate of the animation
  49710. * @returns Highest frame rate of the animation
  49711. */
  49712. Animation.prototype.getHighestFrame = function () {
  49713. var ret = 0;
  49714. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49715. if (ret < this._keys[key].frame) {
  49716. ret = this._keys[key].frame;
  49717. }
  49718. }
  49719. return ret;
  49720. };
  49721. /**
  49722. * Gets the easing function of the animation
  49723. * @returns Easing function of the animation
  49724. */
  49725. Animation.prototype.getEasingFunction = function () {
  49726. return this._easingFunction;
  49727. };
  49728. /**
  49729. * Sets the easing function of the animation
  49730. * @param easingFunction A custom mathematical formula for animation
  49731. */
  49732. Animation.prototype.setEasingFunction = function (easingFunction) {
  49733. this._easingFunction = easingFunction;
  49734. };
  49735. /**
  49736. * Interpolates a scalar linearly
  49737. * @param startValue Start value of the animation curve
  49738. * @param endValue End value of the animation curve
  49739. * @param gradient Scalar amount to interpolate
  49740. * @returns Interpolated scalar value
  49741. */
  49742. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49743. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49744. };
  49745. /**
  49746. * Interpolates a scalar cubically
  49747. * @param startValue Start value of the animation curve
  49748. * @param outTangent End tangent of the animation
  49749. * @param endValue End value of the animation curve
  49750. * @param inTangent Start tangent of the animation curve
  49751. * @param gradient Scalar amount to interpolate
  49752. * @returns Interpolated scalar value
  49753. */
  49754. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49755. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49756. };
  49757. /**
  49758. * Interpolates a quaternion using a spherical linear interpolation
  49759. * @param startValue Start value of the animation curve
  49760. * @param endValue End value of the animation curve
  49761. * @param gradient Scalar amount to interpolate
  49762. * @returns Interpolated quaternion value
  49763. */
  49764. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49765. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49766. };
  49767. /**
  49768. * Interpolates a quaternion cubically
  49769. * @param startValue Start value of the animation curve
  49770. * @param outTangent End tangent of the animation curve
  49771. * @param endValue End value of the animation curve
  49772. * @param inTangent Start tangent of the animation curve
  49773. * @param gradient Scalar amount to interpolate
  49774. * @returns Interpolated quaternion value
  49775. */
  49776. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49777. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49778. };
  49779. /**
  49780. * Interpolates a Vector3 linearl
  49781. * @param startValue Start value of the animation curve
  49782. * @param endValue End value of the animation curve
  49783. * @param gradient Scalar amount to interpolate
  49784. * @returns Interpolated scalar value
  49785. */
  49786. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49787. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49788. };
  49789. /**
  49790. * Interpolates a Vector3 cubically
  49791. * @param startValue Start value of the animation curve
  49792. * @param outTangent End tangent of the animation
  49793. * @param endValue End value of the animation curve
  49794. * @param inTangent Start tangent of the animation curve
  49795. * @param gradient Scalar amount to interpolate
  49796. * @returns InterpolatedVector3 value
  49797. */
  49798. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49799. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49800. };
  49801. /**
  49802. * Interpolates a Vector2 linearly
  49803. * @param startValue Start value of the animation curve
  49804. * @param endValue End value of the animation curve
  49805. * @param gradient Scalar amount to interpolate
  49806. * @returns Interpolated Vector2 value
  49807. */
  49808. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49809. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49810. };
  49811. /**
  49812. * Interpolates a Vector2 cubically
  49813. * @param startValue Start value of the animation curve
  49814. * @param outTangent End tangent of the animation
  49815. * @param endValue End value of the animation curve
  49816. * @param inTangent Start tangent of the animation curve
  49817. * @param gradient Scalar amount to interpolate
  49818. * @returns Interpolated Vector2 value
  49819. */
  49820. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49821. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49822. };
  49823. /**
  49824. * Interpolates a size linearly
  49825. * @param startValue Start value of the animation curve
  49826. * @param endValue End value of the animation curve
  49827. * @param gradient Scalar amount to interpolate
  49828. * @returns Interpolated Size value
  49829. */
  49830. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49831. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49832. };
  49833. /**
  49834. * Interpolates a Color3 linearly
  49835. * @param startValue Start value of the animation curve
  49836. * @param endValue End value of the animation curve
  49837. * @param gradient Scalar amount to interpolate
  49838. * @returns Interpolated Color3 value
  49839. */
  49840. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49841. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49842. };
  49843. /**
  49844. * @hidden Internal use only
  49845. */
  49846. Animation.prototype._getKeyValue = function (value) {
  49847. if (typeof value === "function") {
  49848. return value();
  49849. }
  49850. return value;
  49851. };
  49852. /**
  49853. * @hidden Internal use only
  49854. */
  49855. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49856. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49857. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49858. }
  49859. var keys = this.getKeys();
  49860. // Try to get a hash to find the right key
  49861. 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));
  49862. if (keys[startKeyIndex].frame >= currentFrame) {
  49863. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49864. startKeyIndex--;
  49865. }
  49866. }
  49867. for (var key = startKeyIndex; key < keys.length; key++) {
  49868. var endKey = keys[key + 1];
  49869. if (endKey.frame >= currentFrame) {
  49870. var startKey = keys[key];
  49871. var startValue = this._getKeyValue(startKey.value);
  49872. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49873. return startValue;
  49874. }
  49875. var endValue = this._getKeyValue(endKey.value);
  49876. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49877. var frameDelta = endKey.frame - startKey.frame;
  49878. // gradient : percent of currentFrame between the frame inf and the frame sup
  49879. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49880. // check for easingFunction and correction of gradient
  49881. var easingFunction = this.getEasingFunction();
  49882. if (easingFunction != null) {
  49883. gradient = easingFunction.ease(gradient);
  49884. }
  49885. switch (this.dataType) {
  49886. // Float
  49887. case Animation.ANIMATIONTYPE_FLOAT:
  49888. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49889. switch (loopMode) {
  49890. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49891. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49892. return floatValue;
  49893. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49894. return offsetValue * repeatCount + floatValue;
  49895. }
  49896. break;
  49897. // Quaternion
  49898. case Animation.ANIMATIONTYPE_QUATERNION:
  49899. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49900. switch (loopMode) {
  49901. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49902. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49903. return quatValue;
  49904. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49905. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49906. }
  49907. return quatValue;
  49908. // Vector3
  49909. case Animation.ANIMATIONTYPE_VECTOR3:
  49910. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49911. switch (loopMode) {
  49912. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49913. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49914. return vec3Value;
  49915. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49916. return vec3Value.add(offsetValue.scale(repeatCount));
  49917. }
  49918. // Vector2
  49919. case Animation.ANIMATIONTYPE_VECTOR2:
  49920. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49921. switch (loopMode) {
  49922. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49923. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49924. return vec2Value;
  49925. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49926. return vec2Value.add(offsetValue.scale(repeatCount));
  49927. }
  49928. // Size
  49929. case Animation.ANIMATIONTYPE_SIZE:
  49930. switch (loopMode) {
  49931. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49932. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49933. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49934. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49935. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49936. }
  49937. // Color3
  49938. case Animation.ANIMATIONTYPE_COLOR3:
  49939. switch (loopMode) {
  49940. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49941. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49942. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49943. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49944. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49945. }
  49946. // Matrix
  49947. case Animation.ANIMATIONTYPE_MATRIX:
  49948. switch (loopMode) {
  49949. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49950. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49951. if (Animation.AllowMatricesInterpolation) {
  49952. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49953. }
  49954. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49955. return startValue;
  49956. }
  49957. default:
  49958. break;
  49959. }
  49960. break;
  49961. }
  49962. }
  49963. return this._getKeyValue(keys[keys.length - 1].value);
  49964. };
  49965. /**
  49966. * Defines the function to use to interpolate matrices
  49967. * @param startValue defines the start matrix
  49968. * @param endValue defines the end matrix
  49969. * @param gradient defines the gradient between both matrices
  49970. * @param result defines an optional target matrix where to store the interpolation
  49971. * @returns the interpolated matrix
  49972. */
  49973. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  49974. if (Animation.AllowMatrixDecomposeForInterpolation) {
  49975. if (result) {
  49976. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  49977. return result;
  49978. }
  49979. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  49980. }
  49981. if (result) {
  49982. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  49983. return result;
  49984. }
  49985. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  49986. };
  49987. /**
  49988. * Makes a copy of the animation
  49989. * @returns Cloned animation
  49990. */
  49991. Animation.prototype.clone = function () {
  49992. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  49993. clone.enableBlending = this.enableBlending;
  49994. clone.blendingSpeed = this.blendingSpeed;
  49995. if (this._keys) {
  49996. clone.setKeys(this._keys);
  49997. }
  49998. if (this._ranges) {
  49999. clone._ranges = {};
  50000. for (var name in this._ranges) {
  50001. var range = this._ranges[name];
  50002. if (!range) {
  50003. continue;
  50004. }
  50005. clone._ranges[name] = range.clone();
  50006. }
  50007. }
  50008. return clone;
  50009. };
  50010. /**
  50011. * Sets the key frames of the animation
  50012. * @param values The animation key frames to set
  50013. */
  50014. Animation.prototype.setKeys = function (values) {
  50015. this._keys = values.slice(0);
  50016. };
  50017. /**
  50018. * Serializes the animation to an object
  50019. * @returns Serialized object
  50020. */
  50021. Animation.prototype.serialize = function () {
  50022. var serializationObject = {};
  50023. serializationObject.name = this.name;
  50024. serializationObject.property = this.targetProperty;
  50025. serializationObject.framePerSecond = this.framePerSecond;
  50026. serializationObject.dataType = this.dataType;
  50027. serializationObject.loopBehavior = this.loopMode;
  50028. serializationObject.enableBlending = this.enableBlending;
  50029. serializationObject.blendingSpeed = this.blendingSpeed;
  50030. var dataType = this.dataType;
  50031. serializationObject.keys = [];
  50032. var keys = this.getKeys();
  50033. for (var index = 0; index < keys.length; index++) {
  50034. var animationKey = keys[index];
  50035. var key = {};
  50036. key.frame = animationKey.frame;
  50037. switch (dataType) {
  50038. case Animation.ANIMATIONTYPE_FLOAT:
  50039. key.values = [animationKey.value];
  50040. break;
  50041. case Animation.ANIMATIONTYPE_QUATERNION:
  50042. case Animation.ANIMATIONTYPE_MATRIX:
  50043. case Animation.ANIMATIONTYPE_VECTOR3:
  50044. case Animation.ANIMATIONTYPE_COLOR3:
  50045. key.values = animationKey.value.asArray();
  50046. break;
  50047. }
  50048. serializationObject.keys.push(key);
  50049. }
  50050. serializationObject.ranges = [];
  50051. for (var name in this._ranges) {
  50052. var source = this._ranges[name];
  50053. if (!source) {
  50054. continue;
  50055. }
  50056. var range = {};
  50057. range.name = name;
  50058. range.from = source.from;
  50059. range.to = source.to;
  50060. serializationObject.ranges.push(range);
  50061. }
  50062. return serializationObject;
  50063. };
  50064. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50065. /**
  50066. * Get the float animation type
  50067. */
  50068. get: function () {
  50069. return Animation._ANIMATIONTYPE_FLOAT;
  50070. },
  50071. enumerable: true,
  50072. configurable: true
  50073. });
  50074. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50075. /**
  50076. * Get the Vector3 animation type
  50077. */
  50078. get: function () {
  50079. return Animation._ANIMATIONTYPE_VECTOR3;
  50080. },
  50081. enumerable: true,
  50082. configurable: true
  50083. });
  50084. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50085. /**
  50086. * Get the Vectpr2 animation type
  50087. */
  50088. get: function () {
  50089. return Animation._ANIMATIONTYPE_VECTOR2;
  50090. },
  50091. enumerable: true,
  50092. configurable: true
  50093. });
  50094. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50095. /**
  50096. * Get the Size animation type
  50097. */
  50098. get: function () {
  50099. return Animation._ANIMATIONTYPE_SIZE;
  50100. },
  50101. enumerable: true,
  50102. configurable: true
  50103. });
  50104. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50105. /**
  50106. * Get the Quaternion animation type
  50107. */
  50108. get: function () {
  50109. return Animation._ANIMATIONTYPE_QUATERNION;
  50110. },
  50111. enumerable: true,
  50112. configurable: true
  50113. });
  50114. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50115. /**
  50116. * Get the Matrix animation type
  50117. */
  50118. get: function () {
  50119. return Animation._ANIMATIONTYPE_MATRIX;
  50120. },
  50121. enumerable: true,
  50122. configurable: true
  50123. });
  50124. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50125. /**
  50126. * Get the Color3 animation type
  50127. */
  50128. get: function () {
  50129. return Animation._ANIMATIONTYPE_COLOR3;
  50130. },
  50131. enumerable: true,
  50132. configurable: true
  50133. });
  50134. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50135. /**
  50136. * Get the Relative Loop Mode
  50137. */
  50138. get: function () {
  50139. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50140. },
  50141. enumerable: true,
  50142. configurable: true
  50143. });
  50144. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50145. /**
  50146. * Get the Cycle Loop Mode
  50147. */
  50148. get: function () {
  50149. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50150. },
  50151. enumerable: true,
  50152. configurable: true
  50153. });
  50154. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50155. /**
  50156. * Get the Constant Loop Mode
  50157. */
  50158. get: function () {
  50159. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50160. },
  50161. enumerable: true,
  50162. configurable: true
  50163. });
  50164. /** @hidden */
  50165. Animation._UniversalLerp = function (left, right, amount) {
  50166. var constructor = left.constructor;
  50167. if (constructor.Lerp) { // Lerp supported
  50168. return constructor.Lerp(left, right, amount);
  50169. }
  50170. else if (constructor.Slerp) { // Slerp supported
  50171. return constructor.Slerp(left, right, amount);
  50172. }
  50173. else if (left.toFixed) { // Number
  50174. return left * (1.0 - amount) + amount * right;
  50175. }
  50176. else { // Blending not supported
  50177. return right;
  50178. }
  50179. };
  50180. /**
  50181. * Parses an animation object and creates an animation
  50182. * @param parsedAnimation Parsed animation object
  50183. * @returns Animation object
  50184. */
  50185. Animation.Parse = function (parsedAnimation) {
  50186. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50187. var dataType = parsedAnimation.dataType;
  50188. var keys = [];
  50189. var data;
  50190. var index;
  50191. if (parsedAnimation.enableBlending) {
  50192. animation.enableBlending = parsedAnimation.enableBlending;
  50193. }
  50194. if (parsedAnimation.blendingSpeed) {
  50195. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50196. }
  50197. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50198. var key = parsedAnimation.keys[index];
  50199. var inTangent;
  50200. var outTangent;
  50201. switch (dataType) {
  50202. case Animation.ANIMATIONTYPE_FLOAT:
  50203. data = key.values[0];
  50204. if (key.values.length >= 1) {
  50205. inTangent = key.values[1];
  50206. }
  50207. if (key.values.length >= 2) {
  50208. outTangent = key.values[2];
  50209. }
  50210. break;
  50211. case Animation.ANIMATIONTYPE_QUATERNION:
  50212. data = BABYLON.Quaternion.FromArray(key.values);
  50213. if (key.values.length >= 8) {
  50214. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50215. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50216. inTangent = _inTangent;
  50217. }
  50218. }
  50219. if (key.values.length >= 12) {
  50220. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50221. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50222. outTangent = _outTangent;
  50223. }
  50224. }
  50225. break;
  50226. case Animation.ANIMATIONTYPE_MATRIX:
  50227. data = BABYLON.Matrix.FromArray(key.values);
  50228. break;
  50229. case Animation.ANIMATIONTYPE_COLOR3:
  50230. data = BABYLON.Color3.FromArray(key.values);
  50231. break;
  50232. case Animation.ANIMATIONTYPE_VECTOR3:
  50233. default:
  50234. data = BABYLON.Vector3.FromArray(key.values);
  50235. break;
  50236. }
  50237. var keyData = {};
  50238. keyData.frame = key.frame;
  50239. keyData.value = data;
  50240. if (inTangent != undefined) {
  50241. keyData.inTangent = inTangent;
  50242. }
  50243. if (outTangent != undefined) {
  50244. keyData.outTangent = outTangent;
  50245. }
  50246. keys.push(keyData);
  50247. }
  50248. animation.setKeys(keys);
  50249. if (parsedAnimation.ranges) {
  50250. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50251. data = parsedAnimation.ranges[index];
  50252. animation.createRange(data.name, data.from, data.to);
  50253. }
  50254. }
  50255. return animation;
  50256. };
  50257. /**
  50258. * Appends the serialized animations from the source animations
  50259. * @param source Source containing the animations
  50260. * @param destination Target to store the animations
  50261. */
  50262. Animation.AppendSerializedAnimations = function (source, destination) {
  50263. if (source.animations) {
  50264. destination.animations = [];
  50265. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50266. var animation = source.animations[animationIndex];
  50267. destination.animations.push(animation.serialize());
  50268. }
  50269. }
  50270. };
  50271. /**
  50272. * Use matrix interpolation instead of using direct key value when animating matrices
  50273. */
  50274. Animation.AllowMatricesInterpolation = false;
  50275. /**
  50276. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50277. */
  50278. Animation.AllowMatrixDecomposeForInterpolation = true;
  50279. // Statics
  50280. /**
  50281. * Float animation type
  50282. */
  50283. Animation._ANIMATIONTYPE_FLOAT = 0;
  50284. /**
  50285. * Vector3 animation type
  50286. */
  50287. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50288. /**
  50289. * Quaternion animation type
  50290. */
  50291. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50292. /**
  50293. * Matrix animation type
  50294. */
  50295. Animation._ANIMATIONTYPE_MATRIX = 3;
  50296. /**
  50297. * Color3 animation type
  50298. */
  50299. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50300. /**
  50301. * Vector2 animation type
  50302. */
  50303. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50304. /**
  50305. * Size animation type
  50306. */
  50307. Animation._ANIMATIONTYPE_SIZE = 6;
  50308. /**
  50309. * Relative Loop Mode
  50310. */
  50311. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50312. /**
  50313. * Cycle Loop Mode
  50314. */
  50315. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50316. /**
  50317. * Constant Loop Mode
  50318. */
  50319. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50320. return Animation;
  50321. }());
  50322. BABYLON.Animation = Animation;
  50323. })(BABYLON || (BABYLON = {}));
  50324. //# sourceMappingURL=babylon.animation.js.map
  50325. var BABYLON;
  50326. (function (BABYLON) {
  50327. /**
  50328. * This class defines the direct association between an animation and a target
  50329. */
  50330. var TargetedAnimation = /** @class */ (function () {
  50331. function TargetedAnimation() {
  50332. }
  50333. return TargetedAnimation;
  50334. }());
  50335. BABYLON.TargetedAnimation = TargetedAnimation;
  50336. /**
  50337. * Use this class to create coordinated animations on multiple targets
  50338. */
  50339. var AnimationGroup = /** @class */ (function () {
  50340. function AnimationGroup(name, scene) {
  50341. if (scene === void 0) { scene = null; }
  50342. this.name = name;
  50343. this._targetedAnimations = new Array();
  50344. this._animatables = new Array();
  50345. this._from = Number.MAX_VALUE;
  50346. this._to = -Number.MAX_VALUE;
  50347. this._speedRatio = 1;
  50348. this.onAnimationEndObservable = new BABYLON.Observable();
  50349. /**
  50350. * This observable will notify when all animations have ended.
  50351. */
  50352. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50353. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50354. this._scene.animationGroups.push(this);
  50355. }
  50356. Object.defineProperty(AnimationGroup.prototype, "from", {
  50357. /**
  50358. * Gets the first frame
  50359. */
  50360. get: function () {
  50361. return this._from;
  50362. },
  50363. enumerable: true,
  50364. configurable: true
  50365. });
  50366. Object.defineProperty(AnimationGroup.prototype, "to", {
  50367. /**
  50368. * Gets the last frame
  50369. */
  50370. get: function () {
  50371. return this._to;
  50372. },
  50373. enumerable: true,
  50374. configurable: true
  50375. });
  50376. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50377. /**
  50378. * Define if the animations are started
  50379. */
  50380. get: function () {
  50381. return this._isStarted;
  50382. },
  50383. enumerable: true,
  50384. configurable: true
  50385. });
  50386. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50387. /**
  50388. * Gets or sets the speed ratio to use for all animations
  50389. */
  50390. get: function () {
  50391. return this._speedRatio;
  50392. },
  50393. /**
  50394. * Gets or sets the speed ratio to use for all animations
  50395. */
  50396. set: function (value) {
  50397. if (this._speedRatio === value) {
  50398. return;
  50399. }
  50400. this._speedRatio = value;
  50401. for (var index = 0; index < this._animatables.length; index++) {
  50402. var animatable = this._animatables[index];
  50403. animatable.speedRatio = this._speedRatio;
  50404. }
  50405. },
  50406. enumerable: true,
  50407. configurable: true
  50408. });
  50409. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50410. /**
  50411. * Gets the targeted animations for this animation group
  50412. */
  50413. get: function () {
  50414. return this._targetedAnimations;
  50415. },
  50416. enumerable: true,
  50417. configurable: true
  50418. });
  50419. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50420. /**
  50421. * returning the list of animatables controlled by this animation group.
  50422. */
  50423. get: function () {
  50424. return this._animatables;
  50425. },
  50426. enumerable: true,
  50427. configurable: true
  50428. });
  50429. /**
  50430. * Add an animation (with its target) in the group
  50431. * @param animation defines the animation we want to add
  50432. * @param target defines the target of the animation
  50433. * @returns the {BABYLON.TargetedAnimation} object
  50434. */
  50435. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50436. var targetedAnimation = {
  50437. animation: animation,
  50438. target: target
  50439. };
  50440. var keys = animation.getKeys();
  50441. if (this._from > keys[0].frame) {
  50442. this._from = keys[0].frame;
  50443. }
  50444. if (this._to < keys[keys.length - 1].frame) {
  50445. this._to = keys[keys.length - 1].frame;
  50446. }
  50447. this._targetedAnimations.push(targetedAnimation);
  50448. return targetedAnimation;
  50449. };
  50450. /**
  50451. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50452. * It can add constant keys at begin or end
  50453. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50454. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50455. */
  50456. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50457. if (beginFrame === void 0) { beginFrame = null; }
  50458. if (endFrame === void 0) { endFrame = null; }
  50459. if (beginFrame == null)
  50460. beginFrame = this._from;
  50461. if (endFrame == null)
  50462. endFrame = this._to;
  50463. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50464. var targetedAnimation = this._targetedAnimations[index];
  50465. var keys = targetedAnimation.animation.getKeys();
  50466. var startKey = keys[0];
  50467. var endKey = keys[keys.length - 1];
  50468. if (startKey.frame > beginFrame) {
  50469. var newKey = {
  50470. frame: beginFrame,
  50471. value: startKey.value,
  50472. inTangent: startKey.inTangent,
  50473. outTangent: startKey.outTangent,
  50474. interpolation: startKey.interpolation
  50475. };
  50476. keys.splice(0, 0, newKey);
  50477. }
  50478. if (endKey.frame < endFrame) {
  50479. var newKey = {
  50480. frame: endFrame,
  50481. value: endKey.value,
  50482. inTangent: endKey.outTangent,
  50483. outTangent: endKey.outTangent,
  50484. interpolation: endKey.interpolation
  50485. };
  50486. keys.push(newKey);
  50487. }
  50488. }
  50489. this._from = beginFrame;
  50490. this._to = endFrame;
  50491. return this;
  50492. };
  50493. /**
  50494. * Start all animations on given targets
  50495. * @param loop defines if animations must loop
  50496. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50497. * @param from defines the from key (optional)
  50498. * @param to defines the to key (optional)
  50499. * @returns the current animation group
  50500. */
  50501. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50502. var _this = this;
  50503. if (loop === void 0) { loop = false; }
  50504. if (speedRatio === void 0) { speedRatio = 1; }
  50505. if (this._isStarted || this._targetedAnimations.length === 0) {
  50506. return this;
  50507. }
  50508. var _loop_1 = function (targetedAnimation) {
  50509. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50510. animatable.onAnimationEnd = function () {
  50511. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50512. _this._checkAnimationGroupEnded(animatable);
  50513. };
  50514. this_1._animatables.push(animatable);
  50515. };
  50516. var this_1 = this;
  50517. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50518. var targetedAnimation = _a[_i];
  50519. _loop_1(targetedAnimation);
  50520. }
  50521. this._speedRatio = speedRatio;
  50522. this._isStarted = true;
  50523. return this;
  50524. };
  50525. /**
  50526. * Pause all animations
  50527. */
  50528. AnimationGroup.prototype.pause = function () {
  50529. if (!this._isStarted) {
  50530. return this;
  50531. }
  50532. for (var index = 0; index < this._animatables.length; index++) {
  50533. var animatable = this._animatables[index];
  50534. animatable.pause();
  50535. }
  50536. return this;
  50537. };
  50538. /**
  50539. * Play all animations to initial state
  50540. * This function will start() the animations if they were not started or will restart() them if they were paused
  50541. * @param loop defines if animations must loop
  50542. */
  50543. AnimationGroup.prototype.play = function (loop) {
  50544. // only if all animatables are ready and exist
  50545. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50546. if (loop !== undefined) {
  50547. for (var index = 0; index < this._animatables.length; index++) {
  50548. var animatable = this._animatables[index];
  50549. animatable.loopAnimation = loop;
  50550. }
  50551. }
  50552. this.restart();
  50553. }
  50554. else {
  50555. this.stop();
  50556. this.start(loop, this._speedRatio);
  50557. }
  50558. return this;
  50559. };
  50560. /**
  50561. * Reset all animations to initial state
  50562. */
  50563. AnimationGroup.prototype.reset = function () {
  50564. if (!this._isStarted) {
  50565. return this;
  50566. }
  50567. for (var index = 0; index < this._animatables.length; index++) {
  50568. var animatable = this._animatables[index];
  50569. animatable.reset();
  50570. }
  50571. return this;
  50572. };
  50573. /**
  50574. * Restart animations from key 0
  50575. */
  50576. AnimationGroup.prototype.restart = function () {
  50577. if (!this._isStarted) {
  50578. return this;
  50579. }
  50580. for (var index = 0; index < this._animatables.length; index++) {
  50581. var animatable = this._animatables[index];
  50582. animatable.restart();
  50583. }
  50584. return this;
  50585. };
  50586. /**
  50587. * Stop all animations
  50588. */
  50589. AnimationGroup.prototype.stop = function () {
  50590. if (!this._isStarted) {
  50591. return this;
  50592. }
  50593. var list = this._animatables.slice();
  50594. for (var index = 0; index < list.length; index++) {
  50595. list[index].stop();
  50596. }
  50597. this._isStarted = false;
  50598. return this;
  50599. };
  50600. /**
  50601. * Set animation weight for all animatables
  50602. * @param weight defines the weight to use
  50603. * @return the animationGroup
  50604. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50605. */
  50606. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50607. for (var index = 0; index < this._animatables.length; index++) {
  50608. var animatable = this._animatables[index];
  50609. animatable.weight = weight;
  50610. }
  50611. return this;
  50612. };
  50613. /**
  50614. * Synchronize and normalize all animatables with a source animatable
  50615. * @param root defines the root animatable to synchronize with
  50616. * @return the animationGroup
  50617. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50618. */
  50619. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50620. for (var index = 0; index < this._animatables.length; index++) {
  50621. var animatable = this._animatables[index];
  50622. animatable.syncWith(root);
  50623. }
  50624. return this;
  50625. };
  50626. /**
  50627. * Goes to a specific frame in this animation group
  50628. * @param frame the frame number to go to
  50629. * @return the animationGroup
  50630. */
  50631. AnimationGroup.prototype.goToFrame = function (frame) {
  50632. if (!this._isStarted) {
  50633. return this;
  50634. }
  50635. for (var index = 0; index < this._animatables.length; index++) {
  50636. var animatable = this._animatables[index];
  50637. animatable.goToFrame(frame);
  50638. }
  50639. return this;
  50640. };
  50641. /**
  50642. * Dispose all associated resources
  50643. */
  50644. AnimationGroup.prototype.dispose = function () {
  50645. this._targetedAnimations = [];
  50646. this._animatables = [];
  50647. var index = this._scene.animationGroups.indexOf(this);
  50648. if (index > -1) {
  50649. this._scene.animationGroups.splice(index, 1);
  50650. }
  50651. };
  50652. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50653. // animatable should be taken out of the array
  50654. var idx = this._animatables.indexOf(animatable);
  50655. if (idx > -1) {
  50656. this._animatables.splice(idx, 1);
  50657. }
  50658. // all animatables were removed? animation group ended!
  50659. if (this._animatables.length === 0) {
  50660. this._isStarted = false;
  50661. this.onAnimationGroupEndObservable.notifyObservers(this);
  50662. }
  50663. };
  50664. return AnimationGroup;
  50665. }());
  50666. BABYLON.AnimationGroup = AnimationGroup;
  50667. })(BABYLON || (BABYLON = {}));
  50668. //# sourceMappingURL=babylon.animationGroup.js.map
  50669. var BABYLON;
  50670. (function (BABYLON) {
  50671. /**
  50672. * Defines a runtime animation
  50673. */
  50674. var RuntimeAnimation = /** @class */ (function () {
  50675. /**
  50676. * Create a new RuntimeAnimation object
  50677. * @param target defines the target of the animation
  50678. * @param animation defines the source animation object
  50679. * @param scene defines the hosting scene
  50680. * @param host defines the initiating Animatable
  50681. */
  50682. function RuntimeAnimation(target, animation, scene, host) {
  50683. var _this = this;
  50684. this._events = new Array();
  50685. /**
  50686. * The current frame of the runtime animation
  50687. */
  50688. this._currentFrame = 0;
  50689. /**
  50690. * The original value of the runtime animation
  50691. */
  50692. this._originalValue = new Array();
  50693. /**
  50694. * The offsets cache of the runtime animation
  50695. */
  50696. this._offsetsCache = {};
  50697. /**
  50698. * The high limits cache of the runtime animation
  50699. */
  50700. this._highLimitsCache = {};
  50701. /**
  50702. * Specifies if the runtime animation has been stopped
  50703. */
  50704. this._stopped = false;
  50705. /**
  50706. * The blending factor of the runtime animation
  50707. */
  50708. this._blendingFactor = 0;
  50709. /**
  50710. * The target path of the runtime animation
  50711. */
  50712. this._targetPath = "";
  50713. /**
  50714. * The weight of the runtime animation
  50715. */
  50716. this._weight = 1.0;
  50717. /**
  50718. * The ratio offset of the runtime animation
  50719. */
  50720. this._ratioOffset = 0;
  50721. /**
  50722. * The previous delay of the runtime animation
  50723. */
  50724. this._previousDelay = 0;
  50725. /**
  50726. * The previous ratio of the runtime animation
  50727. */
  50728. this._previousRatio = 0;
  50729. this._animation = animation;
  50730. this._target = target;
  50731. this._scene = scene;
  50732. this._host = host;
  50733. animation._runtimeAnimations.push(this);
  50734. // Cloning events locally
  50735. var events = animation.getEvents();
  50736. if (events && events.length > 0) {
  50737. events.forEach(function (e) {
  50738. _this._events.push(e._clone());
  50739. });
  50740. }
  50741. }
  50742. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50743. /**
  50744. * Gets the current frame of the runtime animation
  50745. */
  50746. get: function () {
  50747. return this._currentFrame;
  50748. },
  50749. enumerable: true,
  50750. configurable: true
  50751. });
  50752. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50753. /**
  50754. * Gets the weight of the runtime animation
  50755. */
  50756. get: function () {
  50757. return this._weight;
  50758. },
  50759. enumerable: true,
  50760. configurable: true
  50761. });
  50762. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50763. /**
  50764. * Gets the current value of the runtime animation
  50765. */
  50766. get: function () {
  50767. return this._currentValue;
  50768. },
  50769. enumerable: true,
  50770. configurable: true
  50771. });
  50772. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50773. /**
  50774. * Gets the target path of the runtime animation
  50775. */
  50776. get: function () {
  50777. return this._targetPath;
  50778. },
  50779. enumerable: true,
  50780. configurable: true
  50781. });
  50782. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50783. /**
  50784. * Gets the actual target of the runtime animation
  50785. */
  50786. get: function () {
  50787. return this._activeTarget;
  50788. },
  50789. enumerable: true,
  50790. configurable: true
  50791. });
  50792. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50793. /**
  50794. * Gets the animation from the runtime animation
  50795. */
  50796. get: function () {
  50797. return this._animation;
  50798. },
  50799. enumerable: true,
  50800. configurable: true
  50801. });
  50802. /**
  50803. * Resets the runtime animation to the beginning
  50804. * @param restoreOriginal defines whether to restore the target property to the original value
  50805. */
  50806. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50807. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50808. if (restoreOriginal) {
  50809. if (this._target instanceof Array) {
  50810. var index = 0;
  50811. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50812. var target = _a[_i];
  50813. if (this._originalValue[index] !== undefined) {
  50814. this._setValue(target, this._originalValue[index], -1);
  50815. }
  50816. index++;
  50817. }
  50818. }
  50819. else {
  50820. if (this._originalValue[0] !== undefined) {
  50821. this._setValue(this._target, this._originalValue[0], -1);
  50822. }
  50823. }
  50824. }
  50825. this._offsetsCache = {};
  50826. this._highLimitsCache = {};
  50827. this._currentFrame = 0;
  50828. this._blendingFactor = 0;
  50829. this._originalValue = new Array();
  50830. // Events
  50831. for (var index = 0; index < this._events.length; index++) {
  50832. this._events[index].isDone = false;
  50833. }
  50834. };
  50835. /**
  50836. * Specifies if the runtime animation is stopped
  50837. * @returns Boolean specifying if the runtime animation is stopped
  50838. */
  50839. RuntimeAnimation.prototype.isStopped = function () {
  50840. return this._stopped;
  50841. };
  50842. /**
  50843. * Disposes of the runtime animation
  50844. */
  50845. RuntimeAnimation.prototype.dispose = function () {
  50846. var index = this._animation.runtimeAnimations.indexOf(this);
  50847. if (index > -1) {
  50848. this._animation.runtimeAnimations.splice(index, 1);
  50849. }
  50850. };
  50851. /**
  50852. * Interpolates the animation from the current frame
  50853. * @param currentFrame The frame to interpolate the animation to
  50854. * @param repeatCount The number of times that the animation should loop
  50855. * @param loopMode The type of looping mode to use
  50856. * @param offsetValue Animation offset value
  50857. * @param highLimitValue The high limit value
  50858. * @returns The interpolated value
  50859. */
  50860. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50861. this._currentFrame = currentFrame;
  50862. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50863. this._workValue = BABYLON.Matrix.Zero();
  50864. }
  50865. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50866. };
  50867. /**
  50868. * Apply the interpolated value to the target
  50869. * @param currentValue defines the value computed by the animation
  50870. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50871. */
  50872. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50873. if (weight === void 0) { weight = 1.0; }
  50874. if (this._target instanceof Array) {
  50875. var index = 0;
  50876. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50877. var target = _a[_i];
  50878. this._setValue(target, currentValue, weight, index);
  50879. index++;
  50880. }
  50881. }
  50882. else {
  50883. this._setValue(this._target, currentValue, weight);
  50884. }
  50885. };
  50886. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50887. if (targetIndex === void 0) { targetIndex = 0; }
  50888. // Set value
  50889. var path;
  50890. var destination;
  50891. var targetPropertyPath = this._animation.targetPropertyPath;
  50892. if (targetPropertyPath.length > 1) {
  50893. var property = target[targetPropertyPath[0]];
  50894. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50895. property = property[targetPropertyPath[index]];
  50896. }
  50897. path = targetPropertyPath[targetPropertyPath.length - 1];
  50898. destination = property;
  50899. }
  50900. else {
  50901. path = targetPropertyPath[0];
  50902. destination = target;
  50903. }
  50904. this._targetPath = path;
  50905. this._activeTarget = destination;
  50906. this._weight = weight;
  50907. if (this._originalValue[targetIndex] === undefined) {
  50908. var originalValue = void 0;
  50909. if (destination.getRestPose && path === "_matrix") { // For bones
  50910. originalValue = destination.getRestPose();
  50911. }
  50912. else {
  50913. originalValue = destination[path];
  50914. }
  50915. if (originalValue && originalValue.clone) {
  50916. this._originalValue[targetIndex] = originalValue.clone();
  50917. }
  50918. else {
  50919. this._originalValue[targetIndex] = originalValue;
  50920. }
  50921. }
  50922. // Blending
  50923. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50924. if (enableBlending && this._blendingFactor <= 1.0) {
  50925. if (!this._originalBlendValue) {
  50926. var originalValue = destination[path];
  50927. if (originalValue.clone) {
  50928. this._originalBlendValue = originalValue.clone();
  50929. }
  50930. else {
  50931. this._originalBlendValue = originalValue;
  50932. }
  50933. }
  50934. if (this._originalBlendValue.m) { // Matrix
  50935. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50936. if (this._currentValue) {
  50937. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50938. }
  50939. else {
  50940. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50941. }
  50942. }
  50943. else {
  50944. if (this._currentValue) {
  50945. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50946. }
  50947. else {
  50948. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50949. }
  50950. }
  50951. }
  50952. else {
  50953. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50954. }
  50955. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50956. this._blendingFactor += blendingSpeed;
  50957. }
  50958. else {
  50959. this._currentValue = currentValue;
  50960. }
  50961. if (weight !== -1.0) {
  50962. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  50963. }
  50964. else {
  50965. destination[path] = this._currentValue;
  50966. }
  50967. if (target.markAsDirty) {
  50968. target.markAsDirty(this._animation.targetProperty);
  50969. }
  50970. };
  50971. /**
  50972. * Gets the loop pmode of the runtime animation
  50973. * @returns Loop Mode
  50974. */
  50975. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  50976. if (this._target && this._target.animationPropertiesOverride) {
  50977. return this._target.animationPropertiesOverride.loopMode;
  50978. }
  50979. return this._animation.loopMode;
  50980. };
  50981. /**
  50982. * Move the current animation to a given frame
  50983. * @param frame defines the frame to move to
  50984. */
  50985. RuntimeAnimation.prototype.goToFrame = function (frame) {
  50986. var keys = this._animation.getKeys();
  50987. if (frame < keys[0].frame) {
  50988. frame = keys[0].frame;
  50989. }
  50990. else if (frame > keys[keys.length - 1].frame) {
  50991. frame = keys[keys.length - 1].frame;
  50992. }
  50993. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  50994. this.setValue(currentValue, -1);
  50995. };
  50996. /**
  50997. * @hidden Internal use only
  50998. */
  50999. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51000. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51001. this._ratioOffset = this._previousRatio - newRatio;
  51002. };
  51003. /**
  51004. * Execute the current animation
  51005. * @param delay defines the delay to add to the current frame
  51006. * @param from defines the lower bound of the animation range
  51007. * @param to defines the upper bound of the animation range
  51008. * @param loop defines if the current animation must loop
  51009. * @param speedRatio defines the current speed ratio
  51010. * @param weight defines the weight of the animation (default is -1 so no weight)
  51011. * @returns a boolean indicating if the animation has ended
  51012. */
  51013. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51014. if (weight === void 0) { weight = -1.0; }
  51015. var targetPropertyPath = this._animation.targetPropertyPath;
  51016. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51017. this._stopped = true;
  51018. return false;
  51019. }
  51020. var keys = this._animation.getKeys();
  51021. // Return immediately if there is only one key frame.
  51022. if (keys.length === 1) {
  51023. this.setValue(keys[0].value, weight);
  51024. return !loop;
  51025. }
  51026. var returnValue = true;
  51027. // Adding a start key at frame 0 if missing
  51028. if (keys[0].frame !== 0) {
  51029. var newKey = { frame: 0, value: keys[0].value };
  51030. keys.splice(0, 0, newKey);
  51031. }
  51032. // Check limits
  51033. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51034. from = keys[0].frame;
  51035. }
  51036. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51037. to = keys[keys.length - 1].frame;
  51038. }
  51039. //to and from cannot be the same key
  51040. if (from === to) {
  51041. if (from > keys[0].frame) {
  51042. from--;
  51043. }
  51044. else if (to < keys[keys.length - 1].frame) {
  51045. to++;
  51046. }
  51047. }
  51048. // Compute ratio
  51049. var range = to - from;
  51050. var offsetValue;
  51051. // ratio represents the frame delta between from and to
  51052. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51053. var highLimitValue = 0;
  51054. this._previousDelay = delay;
  51055. this._previousRatio = ratio;
  51056. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51057. returnValue = false;
  51058. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51059. }
  51060. else {
  51061. // Get max value if required
  51062. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51063. var keyOffset = to.toString() + from.toString();
  51064. if (!this._offsetsCache[keyOffset]) {
  51065. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51066. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51067. switch (this._animation.dataType) {
  51068. // Float
  51069. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51070. this._offsetsCache[keyOffset] = toValue - fromValue;
  51071. break;
  51072. // Quaternion
  51073. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51074. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51075. break;
  51076. // Vector3
  51077. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51078. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51079. // Vector2
  51080. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51081. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51082. // Size
  51083. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51084. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51085. // Color3
  51086. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51087. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51088. default:
  51089. break;
  51090. }
  51091. this._highLimitsCache[keyOffset] = toValue;
  51092. }
  51093. highLimitValue = this._highLimitsCache[keyOffset];
  51094. offsetValue = this._offsetsCache[keyOffset];
  51095. }
  51096. }
  51097. if (offsetValue === undefined) {
  51098. switch (this._animation.dataType) {
  51099. // Float
  51100. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51101. offsetValue = 0;
  51102. break;
  51103. // Quaternion
  51104. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51105. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51106. break;
  51107. // Vector3
  51108. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51109. offsetValue = BABYLON.Vector3.Zero();
  51110. break;
  51111. // Vector2
  51112. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51113. offsetValue = BABYLON.Vector2.Zero();
  51114. break;
  51115. // Size
  51116. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51117. offsetValue = BABYLON.Size.Zero();
  51118. break;
  51119. // Color3
  51120. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51121. offsetValue = BABYLON.Color3.Black();
  51122. }
  51123. }
  51124. // Compute value
  51125. var repeatCount = (ratio / range) >> 0;
  51126. var currentFrame = returnValue ? from + ratio % range : to;
  51127. // Need to normalize?
  51128. if (this._host && this._host.syncRoot) {
  51129. var syncRoot = this._host.syncRoot;
  51130. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51131. currentFrame = from + (to - from) * hostNormalizedFrame;
  51132. }
  51133. // Reset events if looping
  51134. var events = this._events;
  51135. if (range > 0 && this.currentFrame > currentFrame ||
  51136. range < 0 && this.currentFrame < currentFrame) {
  51137. // Need to reset animation events
  51138. for (var index = 0; index < events.length; index++) {
  51139. if (!events[index].onlyOnce) {
  51140. // reset event, the animation is looping
  51141. events[index].isDone = false;
  51142. }
  51143. }
  51144. }
  51145. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51146. // Set value
  51147. this.setValue(currentValue, weight);
  51148. // Check events
  51149. for (var index = 0; index < events.length; index++) {
  51150. // Make sure current frame has passed event frame and that event frame is within the current range
  51151. // Also, handle both forward and reverse animations
  51152. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51153. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51154. var event = events[index];
  51155. if (!event.isDone) {
  51156. // If event should be done only once, remove it.
  51157. if (event.onlyOnce) {
  51158. events.splice(index, 1);
  51159. index--;
  51160. }
  51161. event.isDone = true;
  51162. event.action();
  51163. } // Don't do anything if the event has already be done.
  51164. }
  51165. }
  51166. if (!returnValue) {
  51167. this._stopped = true;
  51168. }
  51169. return returnValue;
  51170. };
  51171. return RuntimeAnimation;
  51172. }());
  51173. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51174. })(BABYLON || (BABYLON = {}));
  51175. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51176. var BABYLON;
  51177. (function (BABYLON) {
  51178. /**
  51179. * Class used to store an actual running animation
  51180. */
  51181. var Animatable = /** @class */ (function () {
  51182. /**
  51183. * Creates a new Animatable
  51184. * @param scene defines the hosting scene
  51185. * @param target defines the target object
  51186. * @param fromFrame defines the starting frame number (default is 0)
  51187. * @param toFrame defines the ending frame number (default is 100)
  51188. * @param loopAnimation defines if the animation must loop (default is false)
  51189. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  51190. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  51191. * @param animations defines a group of animation to add to the new Animatable
  51192. */
  51193. function Animatable(scene,
  51194. /** defines the target object */
  51195. target,
  51196. /** defines the starting frame number (default is 0) */
  51197. fromFrame,
  51198. /** defines the ending frame number (default is 100) */
  51199. toFrame,
  51200. /** defines if the animation must loop (default is false) */
  51201. loopAnimation, speedRatio,
  51202. /** defines a callback to call when animation ends if it is not looping */
  51203. onAnimationEnd, animations) {
  51204. if (fromFrame === void 0) { fromFrame = 0; }
  51205. if (toFrame === void 0) { toFrame = 100; }
  51206. if (loopAnimation === void 0) { loopAnimation = false; }
  51207. if (speedRatio === void 0) { speedRatio = 1.0; }
  51208. this.target = target;
  51209. this.fromFrame = fromFrame;
  51210. this.toFrame = toFrame;
  51211. this.loopAnimation = loopAnimation;
  51212. this.onAnimationEnd = onAnimationEnd;
  51213. this._localDelayOffset = null;
  51214. this._pausedDelay = null;
  51215. this._runtimeAnimations = new Array();
  51216. this._paused = false;
  51217. this._speedRatio = 1;
  51218. this._weight = -1.0;
  51219. /**
  51220. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  51221. * This will only apply for non looping animation (default is true)
  51222. */
  51223. this.disposeOnEnd = true;
  51224. /**
  51225. * Gets a boolean indicating if the animation has started
  51226. */
  51227. this.animationStarted = false;
  51228. /**
  51229. * Observer raised when the animation ends
  51230. */
  51231. this.onAnimationEndObservable = new BABYLON.Observable();
  51232. this._scene = scene;
  51233. if (animations) {
  51234. this.appendAnimations(target, animations);
  51235. }
  51236. this._speedRatio = speedRatio;
  51237. scene._activeAnimatables.push(this);
  51238. }
  51239. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51240. /**
  51241. * Gets the root Animatable used to synchronize and normalize animations
  51242. */
  51243. get: function () {
  51244. return this._syncRoot;
  51245. },
  51246. enumerable: true,
  51247. configurable: true
  51248. });
  51249. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51250. /**
  51251. * Gets the current frame of the first RuntimeAnimation
  51252. * Used to synchronize Animatables
  51253. */
  51254. get: function () {
  51255. if (this._runtimeAnimations.length === 0) {
  51256. return 0;
  51257. }
  51258. return this._runtimeAnimations[0].currentFrame;
  51259. },
  51260. enumerable: true,
  51261. configurable: true
  51262. });
  51263. Object.defineProperty(Animatable.prototype, "weight", {
  51264. /**
  51265. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51266. */
  51267. get: function () {
  51268. return this._weight;
  51269. },
  51270. set: function (value) {
  51271. if (value === -1) { // -1 is ok and means no weight
  51272. this._weight = -1;
  51273. return;
  51274. }
  51275. // Else weight must be in [0, 1] range
  51276. this._weight = Math.min(Math.max(value, 0), 1.0);
  51277. },
  51278. enumerable: true,
  51279. configurable: true
  51280. });
  51281. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51282. /**
  51283. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51284. */
  51285. get: function () {
  51286. return this._speedRatio;
  51287. },
  51288. set: function (value) {
  51289. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51290. var animation = this._runtimeAnimations[index];
  51291. animation._prepareForSpeedRatioChange(value);
  51292. }
  51293. this._speedRatio = value;
  51294. },
  51295. enumerable: true,
  51296. configurable: true
  51297. });
  51298. // Methods
  51299. /**
  51300. * Synchronize and normalize current Animatable with a source Animatable
  51301. * This is useful when using animation weights and when animations are not of the same length
  51302. * @param root defines the root Animatable to synchronize with
  51303. * @returns the current Animatable
  51304. */
  51305. Animatable.prototype.syncWith = function (root) {
  51306. this._syncRoot = root;
  51307. if (root) {
  51308. // Make sure this animatable will animate after the root
  51309. var index = this._scene._activeAnimatables.indexOf(this);
  51310. if (index > -1) {
  51311. this._scene._activeAnimatables.splice(index, 1);
  51312. this._scene._activeAnimatables.push(this);
  51313. }
  51314. }
  51315. return this;
  51316. };
  51317. /**
  51318. * Gets the list of runtime animations
  51319. * @returns an array of RuntimeAnimation
  51320. */
  51321. Animatable.prototype.getAnimations = function () {
  51322. return this._runtimeAnimations;
  51323. };
  51324. /**
  51325. * Adds more animations to the current animatable
  51326. * @param target defines the target of the animations
  51327. * @param animations defines the new animations to add
  51328. */
  51329. Animatable.prototype.appendAnimations = function (target, animations) {
  51330. for (var index = 0; index < animations.length; index++) {
  51331. var animation = animations[index];
  51332. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51333. }
  51334. };
  51335. /**
  51336. * Gets the source animation for a specific property
  51337. * @param property defines the propertyu to look for
  51338. * @returns null or the source animation for the given property
  51339. */
  51340. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51341. var runtimeAnimations = this._runtimeAnimations;
  51342. for (var index = 0; index < runtimeAnimations.length; index++) {
  51343. if (runtimeAnimations[index].animation.targetProperty === property) {
  51344. return runtimeAnimations[index].animation;
  51345. }
  51346. }
  51347. return null;
  51348. };
  51349. /**
  51350. * Gets the runtime animation for a specific property
  51351. * @param property defines the propertyu to look for
  51352. * @returns null or the runtime animation for the given property
  51353. */
  51354. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51355. var runtimeAnimations = this._runtimeAnimations;
  51356. for (var index = 0; index < runtimeAnimations.length; index++) {
  51357. if (runtimeAnimations[index].animation.targetProperty === property) {
  51358. return runtimeAnimations[index];
  51359. }
  51360. }
  51361. return null;
  51362. };
  51363. /**
  51364. * Resets the animatable to its original state
  51365. */
  51366. Animatable.prototype.reset = function () {
  51367. var runtimeAnimations = this._runtimeAnimations;
  51368. for (var index = 0; index < runtimeAnimations.length; index++) {
  51369. runtimeAnimations[index].reset(true);
  51370. }
  51371. this._localDelayOffset = null;
  51372. this._pausedDelay = null;
  51373. };
  51374. /**
  51375. * Allows the animatable to blend with current running animations
  51376. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51377. * @param blendingSpeed defines the blending speed to use
  51378. */
  51379. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51380. var runtimeAnimations = this._runtimeAnimations;
  51381. for (var index = 0; index < runtimeAnimations.length; index++) {
  51382. runtimeAnimations[index].animation.enableBlending = true;
  51383. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51384. }
  51385. };
  51386. /**
  51387. * Disable animation blending
  51388. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  51389. */
  51390. Animatable.prototype.disableBlending = function () {
  51391. var runtimeAnimations = this._runtimeAnimations;
  51392. for (var index = 0; index < runtimeAnimations.length; index++) {
  51393. runtimeAnimations[index].animation.enableBlending = false;
  51394. }
  51395. };
  51396. /**
  51397. * Jump directly to a given frame
  51398. * @param frame defines the frame to jump to
  51399. */
  51400. Animatable.prototype.goToFrame = function (frame) {
  51401. var runtimeAnimations = this._runtimeAnimations;
  51402. if (runtimeAnimations[0]) {
  51403. var fps = runtimeAnimations[0].animation.framePerSecond;
  51404. var currentFrame = runtimeAnimations[0].currentFrame;
  51405. var adjustTime = frame - currentFrame;
  51406. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51407. if (this._localDelayOffset === null) {
  51408. this._localDelayOffset = 0;
  51409. }
  51410. this._localDelayOffset -= delay;
  51411. }
  51412. for (var index = 0; index < runtimeAnimations.length; index++) {
  51413. runtimeAnimations[index].goToFrame(frame);
  51414. }
  51415. };
  51416. /**
  51417. * Pause the animation
  51418. */
  51419. Animatable.prototype.pause = function () {
  51420. if (this._paused) {
  51421. return;
  51422. }
  51423. this._paused = true;
  51424. };
  51425. /**
  51426. * Restart the animation
  51427. */
  51428. Animatable.prototype.restart = function () {
  51429. this._paused = false;
  51430. };
  51431. Animatable.prototype._raiseOnAnimationEnd = function () {
  51432. if (this.onAnimationEnd) {
  51433. this.onAnimationEnd();
  51434. }
  51435. this.onAnimationEndObservable.notifyObservers(this);
  51436. };
  51437. /**
  51438. * Stop and delete the current animation
  51439. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  51440. */
  51441. Animatable.prototype.stop = function (animationName) {
  51442. if (animationName) {
  51443. var idx = this._scene._activeAnimatables.indexOf(this);
  51444. if (idx > -1) {
  51445. var runtimeAnimations = this._runtimeAnimations;
  51446. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51447. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51448. continue;
  51449. }
  51450. runtimeAnimations[index].dispose();
  51451. runtimeAnimations.splice(index, 1);
  51452. }
  51453. if (runtimeAnimations.length == 0) {
  51454. this._scene._activeAnimatables.splice(idx, 1);
  51455. this._raiseOnAnimationEnd();
  51456. }
  51457. }
  51458. }
  51459. else {
  51460. var index = this._scene._activeAnimatables.indexOf(this);
  51461. if (index > -1) {
  51462. this._scene._activeAnimatables.splice(index, 1);
  51463. var runtimeAnimations = this._runtimeAnimations;
  51464. for (var index = 0; index < runtimeAnimations.length; index++) {
  51465. runtimeAnimations[index].dispose();
  51466. }
  51467. this._raiseOnAnimationEnd();
  51468. }
  51469. }
  51470. };
  51471. /**
  51472. * Wait asynchronously for the animation to end
  51473. * @returns a promise which will be fullfilled when the animation ends
  51474. */
  51475. Animatable.prototype.waitAsync = function () {
  51476. var _this = this;
  51477. return new Promise(function (resolve, reject) {
  51478. _this.onAnimationEndObservable.add(function () {
  51479. resolve(_this);
  51480. }, undefined, undefined, _this, true);
  51481. });
  51482. };
  51483. /** @hidden */
  51484. Animatable.prototype._animate = function (delay) {
  51485. if (this._paused) {
  51486. this.animationStarted = false;
  51487. if (this._pausedDelay === null) {
  51488. this._pausedDelay = delay;
  51489. }
  51490. return true;
  51491. }
  51492. if (this._localDelayOffset === null) {
  51493. this._localDelayOffset = delay;
  51494. this._pausedDelay = null;
  51495. }
  51496. else if (this._pausedDelay !== null) {
  51497. this._localDelayOffset += delay - this._pausedDelay;
  51498. this._pausedDelay = null;
  51499. }
  51500. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51501. return true;
  51502. }
  51503. // Animating
  51504. var running = false;
  51505. var runtimeAnimations = this._runtimeAnimations;
  51506. var index;
  51507. for (index = 0; index < runtimeAnimations.length; index++) {
  51508. var animation = runtimeAnimations[index];
  51509. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51510. running = running || isRunning;
  51511. }
  51512. this.animationStarted = running;
  51513. if (!running) {
  51514. if (this.disposeOnEnd) {
  51515. // Remove from active animatables
  51516. index = this._scene._activeAnimatables.indexOf(this);
  51517. this._scene._activeAnimatables.splice(index, 1);
  51518. // Dispose all runtime animations
  51519. for (index = 0; index < runtimeAnimations.length; index++) {
  51520. runtimeAnimations[index].dispose();
  51521. }
  51522. }
  51523. this._raiseOnAnimationEnd();
  51524. if (this.disposeOnEnd) {
  51525. this.onAnimationEnd = null;
  51526. this.onAnimationEndObservable.clear();
  51527. }
  51528. }
  51529. return running;
  51530. };
  51531. return Animatable;
  51532. }());
  51533. BABYLON.Animatable = Animatable;
  51534. })(BABYLON || (BABYLON = {}));
  51535. //# sourceMappingURL=babylon.animatable.js.map
  51536. var BABYLON;
  51537. (function (BABYLON) {
  51538. var EasingFunction = /** @class */ (function () {
  51539. function EasingFunction() {
  51540. // Properties
  51541. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51542. }
  51543. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51544. get: function () {
  51545. return EasingFunction._EASINGMODE_EASEIN;
  51546. },
  51547. enumerable: true,
  51548. configurable: true
  51549. });
  51550. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51551. get: function () {
  51552. return EasingFunction._EASINGMODE_EASEOUT;
  51553. },
  51554. enumerable: true,
  51555. configurable: true
  51556. });
  51557. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51558. get: function () {
  51559. return EasingFunction._EASINGMODE_EASEINOUT;
  51560. },
  51561. enumerable: true,
  51562. configurable: true
  51563. });
  51564. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51565. var n = Math.min(Math.max(easingMode, 0), 2);
  51566. this._easingMode = n;
  51567. };
  51568. EasingFunction.prototype.getEasingMode = function () {
  51569. return this._easingMode;
  51570. };
  51571. EasingFunction.prototype.easeInCore = function (gradient) {
  51572. throw new Error('You must implement this method');
  51573. };
  51574. EasingFunction.prototype.ease = function (gradient) {
  51575. switch (this._easingMode) {
  51576. case EasingFunction.EASINGMODE_EASEIN:
  51577. return this.easeInCore(gradient);
  51578. case EasingFunction.EASINGMODE_EASEOUT:
  51579. return (1 - this.easeInCore(1 - gradient));
  51580. }
  51581. if (gradient >= 0.5) {
  51582. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51583. }
  51584. return (this.easeInCore(gradient * 2) * 0.5);
  51585. };
  51586. //Statics
  51587. EasingFunction._EASINGMODE_EASEIN = 0;
  51588. EasingFunction._EASINGMODE_EASEOUT = 1;
  51589. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51590. return EasingFunction;
  51591. }());
  51592. BABYLON.EasingFunction = EasingFunction;
  51593. var CircleEase = /** @class */ (function (_super) {
  51594. __extends(CircleEase, _super);
  51595. function CircleEase() {
  51596. return _super !== null && _super.apply(this, arguments) || this;
  51597. }
  51598. CircleEase.prototype.easeInCore = function (gradient) {
  51599. gradient = Math.max(0, Math.min(1, gradient));
  51600. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51601. };
  51602. return CircleEase;
  51603. }(EasingFunction));
  51604. BABYLON.CircleEase = CircleEase;
  51605. var BackEase = /** @class */ (function (_super) {
  51606. __extends(BackEase, _super);
  51607. function BackEase(amplitude) {
  51608. if (amplitude === void 0) { amplitude = 1; }
  51609. var _this = _super.call(this) || this;
  51610. _this.amplitude = amplitude;
  51611. return _this;
  51612. }
  51613. BackEase.prototype.easeInCore = function (gradient) {
  51614. var num = Math.max(0, this.amplitude);
  51615. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51616. };
  51617. return BackEase;
  51618. }(EasingFunction));
  51619. BABYLON.BackEase = BackEase;
  51620. var BounceEase = /** @class */ (function (_super) {
  51621. __extends(BounceEase, _super);
  51622. function BounceEase(bounces, bounciness) {
  51623. if (bounces === void 0) { bounces = 3; }
  51624. if (bounciness === void 0) { bounciness = 2; }
  51625. var _this = _super.call(this) || this;
  51626. _this.bounces = bounces;
  51627. _this.bounciness = bounciness;
  51628. return _this;
  51629. }
  51630. BounceEase.prototype.easeInCore = function (gradient) {
  51631. var y = Math.max(0.0, this.bounces);
  51632. var bounciness = this.bounciness;
  51633. if (bounciness <= 1.0) {
  51634. bounciness = 1.001;
  51635. }
  51636. var num9 = Math.pow(bounciness, y);
  51637. var num5 = 1.0 - bounciness;
  51638. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51639. var num15 = gradient * num4;
  51640. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51641. var num3 = Math.floor(num65);
  51642. var num13 = num3 + 1.0;
  51643. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51644. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51645. var num7 = (num8 + num12) * 0.5;
  51646. var num6 = gradient - num7;
  51647. var num2 = num7 - num8;
  51648. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51649. };
  51650. return BounceEase;
  51651. }(EasingFunction));
  51652. BABYLON.BounceEase = BounceEase;
  51653. var CubicEase = /** @class */ (function (_super) {
  51654. __extends(CubicEase, _super);
  51655. function CubicEase() {
  51656. return _super !== null && _super.apply(this, arguments) || this;
  51657. }
  51658. CubicEase.prototype.easeInCore = function (gradient) {
  51659. return (gradient * gradient * gradient);
  51660. };
  51661. return CubicEase;
  51662. }(EasingFunction));
  51663. BABYLON.CubicEase = CubicEase;
  51664. var ElasticEase = /** @class */ (function (_super) {
  51665. __extends(ElasticEase, _super);
  51666. function ElasticEase(oscillations, springiness) {
  51667. if (oscillations === void 0) { oscillations = 3; }
  51668. if (springiness === void 0) { springiness = 3; }
  51669. var _this = _super.call(this) || this;
  51670. _this.oscillations = oscillations;
  51671. _this.springiness = springiness;
  51672. return _this;
  51673. }
  51674. ElasticEase.prototype.easeInCore = function (gradient) {
  51675. var num2;
  51676. var num3 = Math.max(0.0, this.oscillations);
  51677. var num = Math.max(0.0, this.springiness);
  51678. if (num == 0) {
  51679. num2 = gradient;
  51680. }
  51681. else {
  51682. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51683. }
  51684. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51685. };
  51686. return ElasticEase;
  51687. }(EasingFunction));
  51688. BABYLON.ElasticEase = ElasticEase;
  51689. var ExponentialEase = /** @class */ (function (_super) {
  51690. __extends(ExponentialEase, _super);
  51691. function ExponentialEase(exponent) {
  51692. if (exponent === void 0) { exponent = 2; }
  51693. var _this = _super.call(this) || this;
  51694. _this.exponent = exponent;
  51695. return _this;
  51696. }
  51697. ExponentialEase.prototype.easeInCore = function (gradient) {
  51698. if (this.exponent <= 0) {
  51699. return gradient;
  51700. }
  51701. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51702. };
  51703. return ExponentialEase;
  51704. }(EasingFunction));
  51705. BABYLON.ExponentialEase = ExponentialEase;
  51706. var PowerEase = /** @class */ (function (_super) {
  51707. __extends(PowerEase, _super);
  51708. function PowerEase(power) {
  51709. if (power === void 0) { power = 2; }
  51710. var _this = _super.call(this) || this;
  51711. _this.power = power;
  51712. return _this;
  51713. }
  51714. PowerEase.prototype.easeInCore = function (gradient) {
  51715. var y = Math.max(0.0, this.power);
  51716. return Math.pow(gradient, y);
  51717. };
  51718. return PowerEase;
  51719. }(EasingFunction));
  51720. BABYLON.PowerEase = PowerEase;
  51721. var QuadraticEase = /** @class */ (function (_super) {
  51722. __extends(QuadraticEase, _super);
  51723. function QuadraticEase() {
  51724. return _super !== null && _super.apply(this, arguments) || this;
  51725. }
  51726. QuadraticEase.prototype.easeInCore = function (gradient) {
  51727. return (gradient * gradient);
  51728. };
  51729. return QuadraticEase;
  51730. }(EasingFunction));
  51731. BABYLON.QuadraticEase = QuadraticEase;
  51732. var QuarticEase = /** @class */ (function (_super) {
  51733. __extends(QuarticEase, _super);
  51734. function QuarticEase() {
  51735. return _super !== null && _super.apply(this, arguments) || this;
  51736. }
  51737. QuarticEase.prototype.easeInCore = function (gradient) {
  51738. return (gradient * gradient * gradient * gradient);
  51739. };
  51740. return QuarticEase;
  51741. }(EasingFunction));
  51742. BABYLON.QuarticEase = QuarticEase;
  51743. var QuinticEase = /** @class */ (function (_super) {
  51744. __extends(QuinticEase, _super);
  51745. function QuinticEase() {
  51746. return _super !== null && _super.apply(this, arguments) || this;
  51747. }
  51748. QuinticEase.prototype.easeInCore = function (gradient) {
  51749. return (gradient * gradient * gradient * gradient * gradient);
  51750. };
  51751. return QuinticEase;
  51752. }(EasingFunction));
  51753. BABYLON.QuinticEase = QuinticEase;
  51754. var SineEase = /** @class */ (function (_super) {
  51755. __extends(SineEase, _super);
  51756. function SineEase() {
  51757. return _super !== null && _super.apply(this, arguments) || this;
  51758. }
  51759. SineEase.prototype.easeInCore = function (gradient) {
  51760. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51761. };
  51762. return SineEase;
  51763. }(EasingFunction));
  51764. BABYLON.SineEase = SineEase;
  51765. var BezierCurveEase = /** @class */ (function (_super) {
  51766. __extends(BezierCurveEase, _super);
  51767. function BezierCurveEase(x1, y1, x2, y2) {
  51768. if (x1 === void 0) { x1 = 0; }
  51769. if (y1 === void 0) { y1 = 0; }
  51770. if (x2 === void 0) { x2 = 1; }
  51771. if (y2 === void 0) { y2 = 1; }
  51772. var _this = _super.call(this) || this;
  51773. _this.x1 = x1;
  51774. _this.y1 = y1;
  51775. _this.x2 = x2;
  51776. _this.y2 = y2;
  51777. return _this;
  51778. }
  51779. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51780. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51781. };
  51782. return BezierCurveEase;
  51783. }(EasingFunction));
  51784. BABYLON.BezierCurveEase = BezierCurveEase;
  51785. })(BABYLON || (BABYLON = {}));
  51786. //# sourceMappingURL=babylon.easing.js.map
  51787. var BABYLON;
  51788. (function (BABYLON) {
  51789. /**
  51790. * A Condition applied to an Action
  51791. */
  51792. var Condition = /** @class */ (function () {
  51793. /**
  51794. * Creates a new Condition
  51795. * @param actionManager the manager of the action the condition is applied to
  51796. */
  51797. function Condition(actionManager) {
  51798. this._actionManager = actionManager;
  51799. }
  51800. /**
  51801. * Check if the current condition is valid
  51802. * @returns a boolean
  51803. */
  51804. Condition.prototype.isValid = function () {
  51805. return true;
  51806. };
  51807. /**
  51808. * Internal only
  51809. * @hidden
  51810. */
  51811. Condition.prototype._getProperty = function (propertyPath) {
  51812. return this._actionManager._getProperty(propertyPath);
  51813. };
  51814. /**
  51815. * Internal only
  51816. * @hidden
  51817. */
  51818. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51819. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51820. };
  51821. /**
  51822. * Serialize placeholder for child classes
  51823. * @returns the serialized object
  51824. */
  51825. Condition.prototype.serialize = function () {
  51826. };
  51827. /**
  51828. * Internal only
  51829. * @hidden
  51830. */
  51831. Condition.prototype._serialize = function (serializedCondition) {
  51832. return {
  51833. type: 2,
  51834. children: [],
  51835. name: serializedCondition.name,
  51836. properties: serializedCondition.properties
  51837. };
  51838. };
  51839. return Condition;
  51840. }());
  51841. BABYLON.Condition = Condition;
  51842. /**
  51843. * Defines specific conditional operators as extensions of Condition
  51844. */
  51845. var ValueCondition = /** @class */ (function (_super) {
  51846. __extends(ValueCondition, _super);
  51847. /**
  51848. * Creates a new ValueCondition
  51849. * @param actionManager manager for the action the condition applies to
  51850. * @param target for the action
  51851. * @param propertyPath path to specify the property of the target the conditional operator uses
  51852. * @param value the value compared by the conditional operator against the current value of the property
  51853. * @param operator the conditional operator, default ValueCondition.IsEqual
  51854. */
  51855. function ValueCondition(actionManager, target,
  51856. /** path to specify the property of the target the conditional operator uses */
  51857. propertyPath,
  51858. /** the value compared by the conditional operator against the current value of the property */
  51859. value,
  51860. /** the conditional operator, default ValueCondition.IsEqual */
  51861. operator) {
  51862. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51863. var _this = _super.call(this, actionManager) || this;
  51864. _this.propertyPath = propertyPath;
  51865. _this.value = value;
  51866. _this.operator = operator;
  51867. _this._target = target;
  51868. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51869. _this._property = _this._getProperty(_this.propertyPath);
  51870. return _this;
  51871. }
  51872. Object.defineProperty(ValueCondition, "IsEqual", {
  51873. /**
  51874. * returns the number for IsEqual
  51875. */
  51876. get: function () {
  51877. return ValueCondition._IsEqual;
  51878. },
  51879. enumerable: true,
  51880. configurable: true
  51881. });
  51882. Object.defineProperty(ValueCondition, "IsDifferent", {
  51883. /**
  51884. * Returns the number for IsDifferent
  51885. */
  51886. get: function () {
  51887. return ValueCondition._IsDifferent;
  51888. },
  51889. enumerable: true,
  51890. configurable: true
  51891. });
  51892. Object.defineProperty(ValueCondition, "IsGreater", {
  51893. /**
  51894. * Returns the number for IsGreater
  51895. */
  51896. get: function () {
  51897. return ValueCondition._IsGreater;
  51898. },
  51899. enumerable: true,
  51900. configurable: true
  51901. });
  51902. Object.defineProperty(ValueCondition, "IsLesser", {
  51903. /**
  51904. * Returns the number for IsLesser
  51905. */
  51906. get: function () {
  51907. return ValueCondition._IsLesser;
  51908. },
  51909. enumerable: true,
  51910. configurable: true
  51911. });
  51912. /**
  51913. * Compares the given value with the property value for the specified conditional operator
  51914. * @returns the result of the comparison
  51915. */
  51916. ValueCondition.prototype.isValid = function () {
  51917. switch (this.operator) {
  51918. case ValueCondition.IsGreater:
  51919. return this._effectiveTarget[this._property] > this.value;
  51920. case ValueCondition.IsLesser:
  51921. return this._effectiveTarget[this._property] < this.value;
  51922. case ValueCondition.IsEqual:
  51923. case ValueCondition.IsDifferent:
  51924. var check;
  51925. if (this.value.equals) {
  51926. check = this.value.equals(this._effectiveTarget[this._property]);
  51927. }
  51928. else {
  51929. check = this.value === this._effectiveTarget[this._property];
  51930. }
  51931. return this.operator === ValueCondition.IsEqual ? check : !check;
  51932. }
  51933. return false;
  51934. };
  51935. /**
  51936. * Serialize the ValueCondition into a JSON compatible object
  51937. * @returns serialization object
  51938. */
  51939. ValueCondition.prototype.serialize = function () {
  51940. return this._serialize({
  51941. name: "ValueCondition",
  51942. properties: [
  51943. BABYLON.Action._GetTargetProperty(this._target),
  51944. { name: "propertyPath", value: this.propertyPath },
  51945. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51946. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51947. ]
  51948. });
  51949. };
  51950. /**
  51951. * Gets the name of the conditional operator for the ValueCondition
  51952. * @param operator the conditional operator
  51953. * @returns the name
  51954. */
  51955. ValueCondition.GetOperatorName = function (operator) {
  51956. switch (operator) {
  51957. case ValueCondition._IsEqual: return "IsEqual";
  51958. case ValueCondition._IsDifferent: return "IsDifferent";
  51959. case ValueCondition._IsGreater: return "IsGreater";
  51960. case ValueCondition._IsLesser: return "IsLesser";
  51961. default: return "";
  51962. }
  51963. };
  51964. /**
  51965. * Internal only
  51966. * @hidden
  51967. */
  51968. ValueCondition._IsEqual = 0;
  51969. /**
  51970. * Internal only
  51971. * @hidden
  51972. */
  51973. ValueCondition._IsDifferent = 1;
  51974. /**
  51975. * Internal only
  51976. * @hidden
  51977. */
  51978. ValueCondition._IsGreater = 2;
  51979. /**
  51980. * Internal only
  51981. * @hidden
  51982. */
  51983. ValueCondition._IsLesser = 3;
  51984. return ValueCondition;
  51985. }(Condition));
  51986. BABYLON.ValueCondition = ValueCondition;
  51987. /**
  51988. * Defines a predicate condition as an extension of Condition
  51989. */
  51990. var PredicateCondition = /** @class */ (function (_super) {
  51991. __extends(PredicateCondition, _super);
  51992. /**
  51993. * Creates a new PredicateCondition
  51994. * @param actionManager manager for the action the condition applies to
  51995. * @param predicate defines the predicate function used to validate the condition
  51996. */
  51997. function PredicateCondition(actionManager,
  51998. /** defines the predicate function used to validate the condition */
  51999. predicate) {
  52000. var _this = _super.call(this, actionManager) || this;
  52001. _this.predicate = predicate;
  52002. return _this;
  52003. }
  52004. /**
  52005. * @returns the validity of the predicate condition
  52006. */
  52007. PredicateCondition.prototype.isValid = function () {
  52008. return this.predicate();
  52009. };
  52010. return PredicateCondition;
  52011. }(Condition));
  52012. BABYLON.PredicateCondition = PredicateCondition;
  52013. /**
  52014. * Defines a state condition as an extension of Condition
  52015. */
  52016. var StateCondition = /** @class */ (function (_super) {
  52017. __extends(StateCondition, _super);
  52018. /**
  52019. * Creates a new StateCondition
  52020. * @param actionManager manager for the action the condition applies to
  52021. * @param target of the condition
  52022. * @param value to compare with target state
  52023. */
  52024. function StateCondition(actionManager, target, value) {
  52025. var _this = _super.call(this, actionManager) || this;
  52026. _this.value = value;
  52027. _this._target = target;
  52028. return _this;
  52029. }
  52030. /**
  52031. * @returns the validity of the state
  52032. */
  52033. StateCondition.prototype.isValid = function () {
  52034. return this._target.state === this.value;
  52035. };
  52036. /**
  52037. * Serialize the StateCondition into a JSON compatible object
  52038. * @returns serialization object
  52039. */
  52040. StateCondition.prototype.serialize = function () {
  52041. return this._serialize({
  52042. name: "StateCondition",
  52043. properties: [
  52044. BABYLON.Action._GetTargetProperty(this._target),
  52045. { name: "value", value: this.value }
  52046. ]
  52047. });
  52048. };
  52049. return StateCondition;
  52050. }(Condition));
  52051. BABYLON.StateCondition = StateCondition;
  52052. })(BABYLON || (BABYLON = {}));
  52053. //# sourceMappingURL=babylon.condition.js.map
  52054. var BABYLON;
  52055. (function (BABYLON) {
  52056. /**
  52057. * The action to be carried out following a trigger
  52058. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52059. */
  52060. var Action = /** @class */ (function () {
  52061. /**
  52062. * Creates a new Action
  52063. * @param triggerOptions the trigger, with or without parameters, for the action
  52064. * @param condition an optional determinant of action
  52065. */
  52066. function Action(
  52067. /** the trigger, with or without parameters, for the action */
  52068. triggerOptions, condition) {
  52069. this.triggerOptions = triggerOptions;
  52070. /**
  52071. * An event triggered prior to action being executed.
  52072. */
  52073. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52074. if (triggerOptions.parameter) {
  52075. this.trigger = triggerOptions.trigger;
  52076. this._triggerParameter = triggerOptions.parameter;
  52077. }
  52078. else {
  52079. this.trigger = triggerOptions;
  52080. }
  52081. this._nextActiveAction = this;
  52082. this._condition = condition;
  52083. }
  52084. /**
  52085. * Internal only
  52086. * @hidden
  52087. */
  52088. Action.prototype._prepare = function () {
  52089. };
  52090. /**
  52091. * Gets the trigger parameters
  52092. * @returns the trigger parameters
  52093. */
  52094. Action.prototype.getTriggerParameter = function () {
  52095. return this._triggerParameter;
  52096. };
  52097. /**
  52098. * Internal only - executes current action event
  52099. * @hidden
  52100. */
  52101. Action.prototype._executeCurrent = function (evt) {
  52102. if (this._nextActiveAction._condition) {
  52103. var condition = this._nextActiveAction._condition;
  52104. var currentRenderId = this._actionManager.getScene().getRenderId();
  52105. // We cache the current evaluation for the current frame
  52106. if (condition._evaluationId === currentRenderId) {
  52107. if (!condition._currentResult) {
  52108. return;
  52109. }
  52110. }
  52111. else {
  52112. condition._evaluationId = currentRenderId;
  52113. if (!condition.isValid()) {
  52114. condition._currentResult = false;
  52115. return;
  52116. }
  52117. condition._currentResult = true;
  52118. }
  52119. }
  52120. this.onBeforeExecuteObservable.notifyObservers(this);
  52121. this._nextActiveAction.execute(evt);
  52122. this.skipToNextActiveAction();
  52123. };
  52124. /**
  52125. * Execute placeholder for child classes
  52126. * @param evt optional action event
  52127. */
  52128. Action.prototype.execute = function (evt) {
  52129. };
  52130. /**
  52131. * Skips to next active action
  52132. */
  52133. Action.prototype.skipToNextActiveAction = function () {
  52134. if (this._nextActiveAction._child) {
  52135. if (!this._nextActiveAction._child._actionManager) {
  52136. this._nextActiveAction._child._actionManager = this._actionManager;
  52137. }
  52138. this._nextActiveAction = this._nextActiveAction._child;
  52139. }
  52140. else {
  52141. this._nextActiveAction = this;
  52142. }
  52143. };
  52144. /**
  52145. * Adds action to chain of actions, may be a DoNothingAction
  52146. * @param action defines the next action to execute
  52147. * @returns The action passed in
  52148. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52149. */
  52150. Action.prototype.then = function (action) {
  52151. this._child = action;
  52152. action._actionManager = this._actionManager;
  52153. action._prepare();
  52154. return action;
  52155. };
  52156. /**
  52157. * Internal only
  52158. * @hidden
  52159. */
  52160. Action.prototype._getProperty = function (propertyPath) {
  52161. return this._actionManager._getProperty(propertyPath);
  52162. };
  52163. /**
  52164. * Internal only
  52165. * @hidden
  52166. */
  52167. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52168. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52169. };
  52170. /**
  52171. * Serialize placeholder for child classes
  52172. * @param parent of child
  52173. * @returns the serialized object
  52174. */
  52175. Action.prototype.serialize = function (parent) {
  52176. };
  52177. /**
  52178. * Internal only called by serialize
  52179. * @hidden
  52180. */
  52181. Action.prototype._serialize = function (serializedAction, parent) {
  52182. var serializationObject = {
  52183. type: 1,
  52184. children: [],
  52185. name: serializedAction.name,
  52186. properties: serializedAction.properties || []
  52187. };
  52188. // Serialize child
  52189. if (this._child) {
  52190. this._child.serialize(serializationObject);
  52191. }
  52192. // Check if "this" has a condition
  52193. if (this._condition) {
  52194. var serializedCondition = this._condition.serialize();
  52195. serializedCondition.children.push(serializationObject);
  52196. if (parent) {
  52197. parent.children.push(serializedCondition);
  52198. }
  52199. return serializedCondition;
  52200. }
  52201. if (parent) {
  52202. parent.children.push(serializationObject);
  52203. }
  52204. return serializationObject;
  52205. };
  52206. /**
  52207. * Internal only
  52208. * @hidden
  52209. */
  52210. Action._SerializeValueAsString = function (value) {
  52211. if (typeof value === "number") {
  52212. return value.toString();
  52213. }
  52214. if (typeof value === "boolean") {
  52215. return value ? "true" : "false";
  52216. }
  52217. if (value instanceof BABYLON.Vector2) {
  52218. return value.x + ", " + value.y;
  52219. }
  52220. if (value instanceof BABYLON.Vector3) {
  52221. return value.x + ", " + value.y + ", " + value.z;
  52222. }
  52223. if (value instanceof BABYLON.Color3) {
  52224. return value.r + ", " + value.g + ", " + value.b;
  52225. }
  52226. if (value instanceof BABYLON.Color4) {
  52227. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52228. }
  52229. return value; // string
  52230. };
  52231. /**
  52232. * Internal only
  52233. * @hidden
  52234. */
  52235. Action._GetTargetProperty = function (target) {
  52236. return {
  52237. name: "target",
  52238. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52239. : target instanceof BABYLON.Light ? "LightProperties"
  52240. : target instanceof BABYLON.Camera ? "CameraProperties"
  52241. : "SceneProperties",
  52242. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52243. };
  52244. };
  52245. return Action;
  52246. }());
  52247. BABYLON.Action = Action;
  52248. })(BABYLON || (BABYLON = {}));
  52249. //# sourceMappingURL=babylon.action.js.map
  52250. var BABYLON;
  52251. (function (BABYLON) {
  52252. /**
  52253. * ActionEvent is the event being sent when an action is triggered.
  52254. */
  52255. var ActionEvent = /** @class */ (function () {
  52256. /**
  52257. * Creates a new ActionEvent
  52258. * @param source The mesh or sprite that triggered the action
  52259. * @param pointerX The X mouse cursor position at the time of the event
  52260. * @param pointerY The Y mouse cursor position at the time of the event
  52261. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52262. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52263. * @param additionalData additional data for the event
  52264. */
  52265. function ActionEvent(
  52266. /** The mesh or sprite that triggered the action */
  52267. source,
  52268. /** The X mouse cursor position at the time of the event */
  52269. pointerX,
  52270. /** The Y mouse cursor position at the time of the event */
  52271. pointerY,
  52272. /** The mesh that is currently pointed at (can be null) */
  52273. meshUnderPointer,
  52274. /** the original (browser) event that triggered the ActionEvent */
  52275. sourceEvent,
  52276. /** additional data for the event */
  52277. additionalData) {
  52278. this.source = source;
  52279. this.pointerX = pointerX;
  52280. this.pointerY = pointerY;
  52281. this.meshUnderPointer = meshUnderPointer;
  52282. this.sourceEvent = sourceEvent;
  52283. this.additionalData = additionalData;
  52284. }
  52285. /**
  52286. * Helper function to auto-create an ActionEvent from a source mesh.
  52287. * @param source The source mesh that triggered the event
  52288. * @param evt The original (browser) event
  52289. * @param additionalData additional data for the event
  52290. * @returns the new ActionEvent
  52291. */
  52292. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52293. var scene = source.getScene();
  52294. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52295. };
  52296. /**
  52297. * Helper function to auto-create an ActionEvent from a source sprite
  52298. * @param source The source sprite that triggered the event
  52299. * @param scene Scene associated with the sprite
  52300. * @param evt The original (browser) event
  52301. * @param additionalData additional data for the event
  52302. * @returns the new ActionEvent
  52303. */
  52304. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52305. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52306. };
  52307. /**
  52308. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52309. * @param scene the scene where the event occurred
  52310. * @param evt The original (browser) event
  52311. * @returns the new ActionEvent
  52312. */
  52313. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52314. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52315. };
  52316. /**
  52317. * Helper function to auto-create an ActionEvent from a primitive
  52318. * @param prim defines the target primitive
  52319. * @param pointerPos defines the pointer position
  52320. * @param evt The original (browser) event
  52321. * @param additionalData additional data for the event
  52322. * @returns the new ActionEvent
  52323. */
  52324. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52325. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52326. };
  52327. return ActionEvent;
  52328. }());
  52329. BABYLON.ActionEvent = ActionEvent;
  52330. /**
  52331. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52332. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52333. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52334. */
  52335. var ActionManager = /** @class */ (function () {
  52336. /**
  52337. * Creates a new action manager
  52338. * @param scene defines the hosting scene
  52339. */
  52340. function ActionManager(scene) {
  52341. // Members
  52342. /** Gets the list of actions */
  52343. this.actions = new Array();
  52344. /** Gets the cursor to use when hovering items */
  52345. this.hoverCursor = '';
  52346. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52347. scene.actionManagers.push(this);
  52348. }
  52349. Object.defineProperty(ActionManager, "NothingTrigger", {
  52350. /**
  52351. * Nothing
  52352. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52353. */
  52354. get: function () {
  52355. return ActionManager._NothingTrigger;
  52356. },
  52357. enumerable: true,
  52358. configurable: true
  52359. });
  52360. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52361. /**
  52362. * On pick
  52363. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52364. */
  52365. get: function () {
  52366. return ActionManager._OnPickTrigger;
  52367. },
  52368. enumerable: true,
  52369. configurable: true
  52370. });
  52371. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52372. /**
  52373. * On left pick
  52374. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52375. */
  52376. get: function () {
  52377. return ActionManager._OnLeftPickTrigger;
  52378. },
  52379. enumerable: true,
  52380. configurable: true
  52381. });
  52382. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52383. /**
  52384. * On right pick
  52385. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52386. */
  52387. get: function () {
  52388. return ActionManager._OnRightPickTrigger;
  52389. },
  52390. enumerable: true,
  52391. configurable: true
  52392. });
  52393. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52394. /**
  52395. * On center pick
  52396. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52397. */
  52398. get: function () {
  52399. return ActionManager._OnCenterPickTrigger;
  52400. },
  52401. enumerable: true,
  52402. configurable: true
  52403. });
  52404. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52405. /**
  52406. * On pick down
  52407. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52408. */
  52409. get: function () {
  52410. return ActionManager._OnPickDownTrigger;
  52411. },
  52412. enumerable: true,
  52413. configurable: true
  52414. });
  52415. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52416. /**
  52417. * On double pick
  52418. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52419. */
  52420. get: function () {
  52421. return ActionManager._OnDoublePickTrigger;
  52422. },
  52423. enumerable: true,
  52424. configurable: true
  52425. });
  52426. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52427. /**
  52428. * On pick up
  52429. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52430. */
  52431. get: function () {
  52432. return ActionManager._OnPickUpTrigger;
  52433. },
  52434. enumerable: true,
  52435. configurable: true
  52436. });
  52437. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52438. /**
  52439. * On pick out.
  52440. * This trigger will only be raised if you also declared a OnPickDown
  52441. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52442. */
  52443. get: function () {
  52444. return ActionManager._OnPickOutTrigger;
  52445. },
  52446. enumerable: true,
  52447. configurable: true
  52448. });
  52449. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52450. /**
  52451. * On long press
  52452. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52453. */
  52454. get: function () {
  52455. return ActionManager._OnLongPressTrigger;
  52456. },
  52457. enumerable: true,
  52458. configurable: true
  52459. });
  52460. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52461. /**
  52462. * On pointer over
  52463. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52464. */
  52465. get: function () {
  52466. return ActionManager._OnPointerOverTrigger;
  52467. },
  52468. enumerable: true,
  52469. configurable: true
  52470. });
  52471. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52472. /**
  52473. * On pointer out
  52474. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52475. */
  52476. get: function () {
  52477. return ActionManager._OnPointerOutTrigger;
  52478. },
  52479. enumerable: true,
  52480. configurable: true
  52481. });
  52482. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52483. /**
  52484. * On every frame
  52485. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52486. */
  52487. get: function () {
  52488. return ActionManager._OnEveryFrameTrigger;
  52489. },
  52490. enumerable: true,
  52491. configurable: true
  52492. });
  52493. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52494. /**
  52495. * On intersection enter
  52496. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52497. */
  52498. get: function () {
  52499. return ActionManager._OnIntersectionEnterTrigger;
  52500. },
  52501. enumerable: true,
  52502. configurable: true
  52503. });
  52504. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52505. /**
  52506. * On intersection exit
  52507. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52508. */
  52509. get: function () {
  52510. return ActionManager._OnIntersectionExitTrigger;
  52511. },
  52512. enumerable: true,
  52513. configurable: true
  52514. });
  52515. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52516. /**
  52517. * On key down
  52518. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52519. */
  52520. get: function () {
  52521. return ActionManager._OnKeyDownTrigger;
  52522. },
  52523. enumerable: true,
  52524. configurable: true
  52525. });
  52526. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52527. /**
  52528. * On key up
  52529. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52530. */
  52531. get: function () {
  52532. return ActionManager._OnKeyUpTrigger;
  52533. },
  52534. enumerable: true,
  52535. configurable: true
  52536. });
  52537. // Methods
  52538. /**
  52539. * Releases all associated resources
  52540. */
  52541. ActionManager.prototype.dispose = function () {
  52542. var index = this._scene.actionManagers.indexOf(this);
  52543. for (var i = 0; i < this.actions.length; i++) {
  52544. var action = this.actions[i];
  52545. ActionManager.Triggers[action.trigger]--;
  52546. if (ActionManager.Triggers[action.trigger] === 0) {
  52547. delete ActionManager.Triggers[action.trigger];
  52548. }
  52549. }
  52550. if (index > -1) {
  52551. this._scene.actionManagers.splice(index, 1);
  52552. }
  52553. };
  52554. /**
  52555. * Gets hosting scene
  52556. * @returns the hosting scene
  52557. */
  52558. ActionManager.prototype.getScene = function () {
  52559. return this._scene;
  52560. };
  52561. /**
  52562. * Does this action manager handles actions of any of the given triggers
  52563. * @param triggers defines the triggers to be tested
  52564. * @return a boolean indicating whether one (or more) of the triggers is handled
  52565. */
  52566. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52567. for (var index = 0; index < this.actions.length; index++) {
  52568. var action = this.actions[index];
  52569. if (triggers.indexOf(action.trigger) > -1) {
  52570. return true;
  52571. }
  52572. }
  52573. return false;
  52574. };
  52575. /**
  52576. * Does this action manager handles actions of a given trigger
  52577. * @param trigger defines the trigger to be tested
  52578. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52579. * @return whether the trigger is handled
  52580. */
  52581. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52582. for (var index = 0; index < this.actions.length; index++) {
  52583. var action = this.actions[index];
  52584. if (action.trigger === trigger) {
  52585. if (parameterPredicate) {
  52586. if (parameterPredicate(action.getTriggerParameter())) {
  52587. return true;
  52588. }
  52589. }
  52590. else {
  52591. return true;
  52592. }
  52593. }
  52594. }
  52595. return false;
  52596. };
  52597. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52598. /**
  52599. * Does this action manager has pointer triggers
  52600. */
  52601. get: function () {
  52602. for (var index = 0; index < this.actions.length; index++) {
  52603. var action = this.actions[index];
  52604. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52605. return true;
  52606. }
  52607. }
  52608. return false;
  52609. },
  52610. enumerable: true,
  52611. configurable: true
  52612. });
  52613. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52614. /**
  52615. * Does this action manager has pick triggers
  52616. */
  52617. get: function () {
  52618. for (var index = 0; index < this.actions.length; index++) {
  52619. var action = this.actions[index];
  52620. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52621. return true;
  52622. }
  52623. }
  52624. return false;
  52625. },
  52626. enumerable: true,
  52627. configurable: true
  52628. });
  52629. Object.defineProperty(ActionManager, "HasTriggers", {
  52630. /**
  52631. * Does exist one action manager with at least one trigger
  52632. **/
  52633. get: function () {
  52634. for (var t in ActionManager.Triggers) {
  52635. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52636. return true;
  52637. }
  52638. }
  52639. return false;
  52640. },
  52641. enumerable: true,
  52642. configurable: true
  52643. });
  52644. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52645. /**
  52646. * Does exist one action manager with at least one pick trigger
  52647. **/
  52648. get: function () {
  52649. for (var t in ActionManager.Triggers) {
  52650. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52651. var t_int = parseInt(t);
  52652. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52653. return true;
  52654. }
  52655. }
  52656. }
  52657. return false;
  52658. },
  52659. enumerable: true,
  52660. configurable: true
  52661. });
  52662. /**
  52663. * Does exist one action manager that handles actions of a given trigger
  52664. * @param trigger defines the trigger to be tested
  52665. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52666. **/
  52667. ActionManager.HasSpecificTrigger = function (trigger) {
  52668. for (var t in ActionManager.Triggers) {
  52669. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52670. var t_int = parseInt(t);
  52671. if (t_int === trigger) {
  52672. return true;
  52673. }
  52674. }
  52675. }
  52676. return false;
  52677. };
  52678. /**
  52679. * Registers an action to this action manager
  52680. * @param action defines the action to be registered
  52681. * @return the action amended (prepared) after registration
  52682. */
  52683. ActionManager.prototype.registerAction = function (action) {
  52684. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52685. if (this.getScene().actionManager !== this) {
  52686. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52687. return null;
  52688. }
  52689. }
  52690. this.actions.push(action);
  52691. if (ActionManager.Triggers[action.trigger]) {
  52692. ActionManager.Triggers[action.trigger]++;
  52693. }
  52694. else {
  52695. ActionManager.Triggers[action.trigger] = 1;
  52696. }
  52697. action._actionManager = this;
  52698. action._prepare();
  52699. return action;
  52700. };
  52701. /**
  52702. * Unregisters an action to this action manager
  52703. * @param action defines the action to be unregistered
  52704. * @return a boolean indicating whether the action has been unregistered
  52705. */
  52706. ActionManager.prototype.unregisterAction = function (action) {
  52707. var index = this.actions.indexOf(action);
  52708. if (index !== -1) {
  52709. this.actions.splice(index, 1);
  52710. ActionManager.Triggers[action.trigger] -= 1;
  52711. if (ActionManager.Triggers[action.trigger] === 0) {
  52712. delete ActionManager.Triggers[action.trigger];
  52713. }
  52714. delete action._actionManager;
  52715. return true;
  52716. }
  52717. return false;
  52718. };
  52719. /**
  52720. * Process a specific trigger
  52721. * @param trigger defines the trigger to process
  52722. * @param evt defines the event details to be processed
  52723. */
  52724. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52725. for (var index = 0; index < this.actions.length; index++) {
  52726. var action = this.actions[index];
  52727. if (action.trigger === trigger) {
  52728. if (evt) {
  52729. if (trigger === ActionManager.OnKeyUpTrigger
  52730. || trigger === ActionManager.OnKeyDownTrigger) {
  52731. var parameter = action.getTriggerParameter();
  52732. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52733. if (!parameter.toLowerCase) {
  52734. continue;
  52735. }
  52736. var lowerCase = parameter.toLowerCase();
  52737. if (lowerCase !== evt.sourceEvent.key) {
  52738. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52739. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52740. if (actualkey !== lowerCase) {
  52741. continue;
  52742. }
  52743. }
  52744. }
  52745. }
  52746. }
  52747. action._executeCurrent(evt);
  52748. }
  52749. }
  52750. };
  52751. /** @hidden */
  52752. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52753. var properties = propertyPath.split(".");
  52754. for (var index = 0; index < properties.length - 1; index++) {
  52755. target = target[properties[index]];
  52756. }
  52757. return target;
  52758. };
  52759. /** @hidden */
  52760. ActionManager.prototype._getProperty = function (propertyPath) {
  52761. var properties = propertyPath.split(".");
  52762. return properties[properties.length - 1];
  52763. };
  52764. /**
  52765. * Serialize this manager to a JSON object
  52766. * @param name defines the property name to store this manager
  52767. * @returns a JSON representation of this manager
  52768. */
  52769. ActionManager.prototype.serialize = function (name) {
  52770. var root = {
  52771. children: new Array(),
  52772. name: name,
  52773. type: 3,
  52774. properties: new Array() // Empty for root but required
  52775. };
  52776. for (var i = 0; i < this.actions.length; i++) {
  52777. var triggerObject = {
  52778. type: 0,
  52779. children: new Array(),
  52780. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52781. properties: new Array()
  52782. };
  52783. var triggerOptions = this.actions[i].triggerOptions;
  52784. if (triggerOptions && typeof triggerOptions !== "number") {
  52785. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52786. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52787. }
  52788. else {
  52789. var parameter = {};
  52790. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52791. if (triggerOptions.parameter.mesh) {
  52792. parameter._meshId = triggerOptions.parameter.mesh.id;
  52793. }
  52794. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52795. }
  52796. }
  52797. // Serialize child action, recursively
  52798. this.actions[i].serialize(triggerObject);
  52799. // Add serialized trigger
  52800. root.children.push(triggerObject);
  52801. }
  52802. return root;
  52803. };
  52804. /**
  52805. * Creates a new ActionManager from a JSON data
  52806. * @param parsedActions defines the JSON data to read from
  52807. * @param object defines the hosting mesh
  52808. * @param scene defines the hosting scene
  52809. */
  52810. ActionManager.Parse = function (parsedActions, object, scene) {
  52811. var actionManager = new ActionManager(scene);
  52812. if (object === null)
  52813. scene.actionManager = actionManager;
  52814. else
  52815. object.actionManager = actionManager;
  52816. // instanciate a new object
  52817. var instanciate = function (name, params) {
  52818. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52819. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52820. newInstance.constructor.apply(newInstance, params);
  52821. return newInstance;
  52822. };
  52823. var parseParameter = function (name, value, target, propertyPath) {
  52824. if (propertyPath === null) {
  52825. // String, boolean or float
  52826. var floatValue = parseFloat(value);
  52827. if (value === "true" || value === "false")
  52828. return value === "true";
  52829. else
  52830. return isNaN(floatValue) ? value : floatValue;
  52831. }
  52832. var effectiveTarget = propertyPath.split(".");
  52833. var values = value.split(",");
  52834. // Get effective Target
  52835. for (var i = 0; i < effectiveTarget.length; i++) {
  52836. target = target[effectiveTarget[i]];
  52837. }
  52838. // Return appropriate value with its type
  52839. if (typeof (target) === "boolean")
  52840. return values[0] === "true";
  52841. if (typeof (target) === "string")
  52842. return values[0];
  52843. // Parameters with multiple values such as Vector3 etc.
  52844. var split = new Array();
  52845. for (var i = 0; i < values.length; i++)
  52846. split.push(parseFloat(values[i]));
  52847. if (target instanceof BABYLON.Vector3)
  52848. return BABYLON.Vector3.FromArray(split);
  52849. if (target instanceof BABYLON.Vector4)
  52850. return BABYLON.Vector4.FromArray(split);
  52851. if (target instanceof BABYLON.Color3)
  52852. return BABYLON.Color3.FromArray(split);
  52853. if (target instanceof BABYLON.Color4)
  52854. return BABYLON.Color4.FromArray(split);
  52855. return parseFloat(values[0]);
  52856. };
  52857. // traverse graph per trigger
  52858. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52859. if (combineArray === void 0) { combineArray = null; }
  52860. if (parsedAction.detached)
  52861. return;
  52862. var parameters = new Array();
  52863. var target = null;
  52864. var propertyPath = null;
  52865. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52866. // Parameters
  52867. if (parsedAction.type === 2)
  52868. parameters.push(actionManager);
  52869. else
  52870. parameters.push(trigger);
  52871. if (combine) {
  52872. var actions = new Array();
  52873. for (var j = 0; j < parsedAction.combine.length; j++) {
  52874. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52875. }
  52876. parameters.push(actions);
  52877. }
  52878. else {
  52879. for (var i = 0; i < parsedAction.properties.length; i++) {
  52880. var value = parsedAction.properties[i].value;
  52881. var name = parsedAction.properties[i].name;
  52882. var targetType = parsedAction.properties[i].targetType;
  52883. if (name === "target")
  52884. if (targetType !== null && targetType === "SceneProperties")
  52885. value = target = scene;
  52886. else
  52887. value = target = scene.getNodeByName(value);
  52888. else if (name === "parent")
  52889. value = scene.getNodeByName(value);
  52890. else if (name === "sound")
  52891. value = scene.getSoundByName(value);
  52892. else if (name !== "propertyPath") {
  52893. if (parsedAction.type === 2 && name === "operator")
  52894. value = BABYLON.ValueCondition[value];
  52895. else
  52896. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52897. }
  52898. else {
  52899. propertyPath = value;
  52900. }
  52901. parameters.push(value);
  52902. }
  52903. }
  52904. if (combineArray === null) {
  52905. parameters.push(condition);
  52906. }
  52907. else {
  52908. parameters.push(null);
  52909. }
  52910. // If interpolate value action
  52911. if (parsedAction.name === "InterpolateValueAction") {
  52912. var param = parameters[parameters.length - 2];
  52913. parameters[parameters.length - 1] = param;
  52914. parameters[parameters.length - 2] = condition;
  52915. }
  52916. // Action or condition(s) and not CombineAction
  52917. var newAction = instanciate(parsedAction.name, parameters);
  52918. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52919. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52920. if (action)
  52921. action.then(nothing);
  52922. else
  52923. actionManager.registerAction(nothing);
  52924. action = nothing;
  52925. }
  52926. if (combineArray === null) {
  52927. if (newAction instanceof BABYLON.Condition) {
  52928. condition = newAction;
  52929. newAction = action;
  52930. }
  52931. else {
  52932. condition = null;
  52933. if (action)
  52934. action.then(newAction);
  52935. else
  52936. actionManager.registerAction(newAction);
  52937. }
  52938. }
  52939. else {
  52940. combineArray.push(newAction);
  52941. }
  52942. for (var i = 0; i < parsedAction.children.length; i++)
  52943. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52944. };
  52945. // triggers
  52946. for (var i = 0; i < parsedActions.children.length; i++) {
  52947. var triggerParams;
  52948. var trigger = parsedActions.children[i];
  52949. if (trigger.properties.length > 0) {
  52950. var param = trigger.properties[0].value;
  52951. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52952. if (value._meshId) {
  52953. value.mesh = scene.getMeshByID(value._meshId);
  52954. }
  52955. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52956. }
  52957. else
  52958. triggerParams = ActionManager[trigger.name];
  52959. for (var j = 0; j < trigger.children.length; j++) {
  52960. if (!trigger.detached)
  52961. traverse(trigger.children[j], triggerParams, null, null);
  52962. }
  52963. }
  52964. };
  52965. /**
  52966. * Get a trigger name by index
  52967. * @param trigger defines the trigger index
  52968. * @returns a trigger name
  52969. */
  52970. ActionManager.GetTriggerName = function (trigger) {
  52971. switch (trigger) {
  52972. case 0: return "NothingTrigger";
  52973. case 1: return "OnPickTrigger";
  52974. case 2: return "OnLeftPickTrigger";
  52975. case 3: return "OnRightPickTrigger";
  52976. case 4: return "OnCenterPickTrigger";
  52977. case 5: return "OnPickDownTrigger";
  52978. case 6: return "OnPickUpTrigger";
  52979. case 7: return "OnLongPressTrigger";
  52980. case 8: return "OnPointerOverTrigger";
  52981. case 9: return "OnPointerOutTrigger";
  52982. case 10: return "OnEveryFrameTrigger";
  52983. case 11: return "OnIntersectionEnterTrigger";
  52984. case 12: return "OnIntersectionExitTrigger";
  52985. case 13: return "OnKeyDownTrigger";
  52986. case 14: return "OnKeyUpTrigger";
  52987. case 15: return "OnPickOutTrigger";
  52988. default: return "";
  52989. }
  52990. };
  52991. // Statics
  52992. ActionManager._NothingTrigger = 0;
  52993. ActionManager._OnPickTrigger = 1;
  52994. ActionManager._OnLeftPickTrigger = 2;
  52995. ActionManager._OnRightPickTrigger = 3;
  52996. ActionManager._OnCenterPickTrigger = 4;
  52997. ActionManager._OnPickDownTrigger = 5;
  52998. ActionManager._OnDoublePickTrigger = 6;
  52999. ActionManager._OnPickUpTrigger = 7;
  53000. ActionManager._OnLongPressTrigger = 8;
  53001. ActionManager._OnPointerOverTrigger = 9;
  53002. ActionManager._OnPointerOutTrigger = 10;
  53003. ActionManager._OnEveryFrameTrigger = 11;
  53004. ActionManager._OnIntersectionEnterTrigger = 12;
  53005. ActionManager._OnIntersectionExitTrigger = 13;
  53006. ActionManager._OnKeyDownTrigger = 14;
  53007. ActionManager._OnKeyUpTrigger = 15;
  53008. ActionManager._OnPickOutTrigger = 16;
  53009. /** Gets the list of active triggers */
  53010. ActionManager.Triggers = {};
  53011. return ActionManager;
  53012. }());
  53013. BABYLON.ActionManager = ActionManager;
  53014. })(BABYLON || (BABYLON = {}));
  53015. //# sourceMappingURL=babylon.actionManager.js.map
  53016. var BABYLON;
  53017. (function (BABYLON) {
  53018. var InterpolateValueAction = /** @class */ (function (_super) {
  53019. __extends(InterpolateValueAction, _super);
  53020. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53021. if (duration === void 0) { duration = 1000; }
  53022. var _this = _super.call(this, triggerOptions, condition) || this;
  53023. _this.propertyPath = propertyPath;
  53024. _this.value = value;
  53025. _this.duration = duration;
  53026. _this.stopOtherAnimations = stopOtherAnimations;
  53027. _this.onInterpolationDone = onInterpolationDone;
  53028. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53029. _this._target = _this._effectiveTarget = target;
  53030. return _this;
  53031. }
  53032. InterpolateValueAction.prototype._prepare = function () {
  53033. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53034. this._property = this._getProperty(this.propertyPath);
  53035. };
  53036. InterpolateValueAction.prototype.execute = function () {
  53037. var _this = this;
  53038. var scene = this._actionManager.getScene();
  53039. var keys = [
  53040. {
  53041. frame: 0,
  53042. value: this._effectiveTarget[this._property]
  53043. }, {
  53044. frame: 100,
  53045. value: this.value
  53046. }
  53047. ];
  53048. var dataType;
  53049. if (typeof this.value === "number") {
  53050. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53051. }
  53052. else if (this.value instanceof BABYLON.Color3) {
  53053. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53054. }
  53055. else if (this.value instanceof BABYLON.Vector3) {
  53056. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53057. }
  53058. else if (this.value instanceof BABYLON.Matrix) {
  53059. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53060. }
  53061. else if (this.value instanceof BABYLON.Quaternion) {
  53062. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53063. }
  53064. else {
  53065. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53066. return;
  53067. }
  53068. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53069. animation.setKeys(keys);
  53070. if (this.stopOtherAnimations) {
  53071. scene.stopAnimation(this._effectiveTarget);
  53072. }
  53073. var wrapper = function () {
  53074. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53075. if (_this.onInterpolationDone) {
  53076. _this.onInterpolationDone();
  53077. }
  53078. };
  53079. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53080. };
  53081. InterpolateValueAction.prototype.serialize = function (parent) {
  53082. return _super.prototype._serialize.call(this, {
  53083. name: "InterpolateValueAction",
  53084. properties: [
  53085. BABYLON.Action._GetTargetProperty(this._target),
  53086. { name: "propertyPath", value: this.propertyPath },
  53087. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53088. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53089. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53090. ]
  53091. }, parent);
  53092. };
  53093. return InterpolateValueAction;
  53094. }(BABYLON.Action));
  53095. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53096. })(BABYLON || (BABYLON = {}));
  53097. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53098. var BABYLON;
  53099. (function (BABYLON) {
  53100. var SwitchBooleanAction = /** @class */ (function (_super) {
  53101. __extends(SwitchBooleanAction, _super);
  53102. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53103. var _this = _super.call(this, triggerOptions, condition) || this;
  53104. _this.propertyPath = propertyPath;
  53105. _this._target = _this._effectiveTarget = target;
  53106. return _this;
  53107. }
  53108. SwitchBooleanAction.prototype._prepare = function () {
  53109. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53110. this._property = this._getProperty(this.propertyPath);
  53111. };
  53112. SwitchBooleanAction.prototype.execute = function () {
  53113. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53114. };
  53115. SwitchBooleanAction.prototype.serialize = function (parent) {
  53116. return _super.prototype._serialize.call(this, {
  53117. name: "SwitchBooleanAction",
  53118. properties: [
  53119. BABYLON.Action._GetTargetProperty(this._target),
  53120. { name: "propertyPath", value: this.propertyPath }
  53121. ]
  53122. }, parent);
  53123. };
  53124. return SwitchBooleanAction;
  53125. }(BABYLON.Action));
  53126. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53127. var SetStateAction = /** @class */ (function (_super) {
  53128. __extends(SetStateAction, _super);
  53129. function SetStateAction(triggerOptions, target, value, condition) {
  53130. var _this = _super.call(this, triggerOptions, condition) || this;
  53131. _this.value = value;
  53132. _this._target = target;
  53133. return _this;
  53134. }
  53135. SetStateAction.prototype.execute = function () {
  53136. this._target.state = this.value;
  53137. };
  53138. SetStateAction.prototype.serialize = function (parent) {
  53139. return _super.prototype._serialize.call(this, {
  53140. name: "SetStateAction",
  53141. properties: [
  53142. BABYLON.Action._GetTargetProperty(this._target),
  53143. { name: "value", value: this.value }
  53144. ]
  53145. }, parent);
  53146. };
  53147. return SetStateAction;
  53148. }(BABYLON.Action));
  53149. BABYLON.SetStateAction = SetStateAction;
  53150. var SetValueAction = /** @class */ (function (_super) {
  53151. __extends(SetValueAction, _super);
  53152. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53153. var _this = _super.call(this, triggerOptions, condition) || this;
  53154. _this.propertyPath = propertyPath;
  53155. _this.value = value;
  53156. _this._target = _this._effectiveTarget = target;
  53157. return _this;
  53158. }
  53159. SetValueAction.prototype._prepare = function () {
  53160. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53161. this._property = this._getProperty(this.propertyPath);
  53162. };
  53163. SetValueAction.prototype.execute = function () {
  53164. this._effectiveTarget[this._property] = this.value;
  53165. if (this._target.markAsDirty) {
  53166. this._target.markAsDirty(this._property);
  53167. }
  53168. };
  53169. SetValueAction.prototype.serialize = function (parent) {
  53170. return _super.prototype._serialize.call(this, {
  53171. name: "SetValueAction",
  53172. properties: [
  53173. BABYLON.Action._GetTargetProperty(this._target),
  53174. { name: "propertyPath", value: this.propertyPath },
  53175. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53176. ]
  53177. }, parent);
  53178. };
  53179. return SetValueAction;
  53180. }(BABYLON.Action));
  53181. BABYLON.SetValueAction = SetValueAction;
  53182. var IncrementValueAction = /** @class */ (function (_super) {
  53183. __extends(IncrementValueAction, _super);
  53184. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53185. var _this = _super.call(this, triggerOptions, condition) || this;
  53186. _this.propertyPath = propertyPath;
  53187. _this.value = value;
  53188. _this._target = _this._effectiveTarget = target;
  53189. return _this;
  53190. }
  53191. IncrementValueAction.prototype._prepare = function () {
  53192. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53193. this._property = this._getProperty(this.propertyPath);
  53194. if (typeof this._effectiveTarget[this._property] !== "number") {
  53195. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53196. }
  53197. };
  53198. IncrementValueAction.prototype.execute = function () {
  53199. this._effectiveTarget[this._property] += this.value;
  53200. if (this._target.markAsDirty) {
  53201. this._target.markAsDirty(this._property);
  53202. }
  53203. };
  53204. IncrementValueAction.prototype.serialize = function (parent) {
  53205. return _super.prototype._serialize.call(this, {
  53206. name: "IncrementValueAction",
  53207. properties: [
  53208. BABYLON.Action._GetTargetProperty(this._target),
  53209. { name: "propertyPath", value: this.propertyPath },
  53210. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53211. ]
  53212. }, parent);
  53213. };
  53214. return IncrementValueAction;
  53215. }(BABYLON.Action));
  53216. BABYLON.IncrementValueAction = IncrementValueAction;
  53217. var PlayAnimationAction = /** @class */ (function (_super) {
  53218. __extends(PlayAnimationAction, _super);
  53219. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53220. var _this = _super.call(this, triggerOptions, condition) || this;
  53221. _this.from = from;
  53222. _this.to = to;
  53223. _this.loop = loop;
  53224. _this._target = target;
  53225. return _this;
  53226. }
  53227. PlayAnimationAction.prototype._prepare = function () {
  53228. };
  53229. PlayAnimationAction.prototype.execute = function () {
  53230. var scene = this._actionManager.getScene();
  53231. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53232. };
  53233. PlayAnimationAction.prototype.serialize = function (parent) {
  53234. return _super.prototype._serialize.call(this, {
  53235. name: "PlayAnimationAction",
  53236. properties: [
  53237. BABYLON.Action._GetTargetProperty(this._target),
  53238. { name: "from", value: String(this.from) },
  53239. { name: "to", value: String(this.to) },
  53240. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53241. ]
  53242. }, parent);
  53243. };
  53244. return PlayAnimationAction;
  53245. }(BABYLON.Action));
  53246. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53247. var StopAnimationAction = /** @class */ (function (_super) {
  53248. __extends(StopAnimationAction, _super);
  53249. function StopAnimationAction(triggerOptions, target, condition) {
  53250. var _this = _super.call(this, triggerOptions, condition) || this;
  53251. _this._target = target;
  53252. return _this;
  53253. }
  53254. StopAnimationAction.prototype._prepare = function () {
  53255. };
  53256. StopAnimationAction.prototype.execute = function () {
  53257. var scene = this._actionManager.getScene();
  53258. scene.stopAnimation(this._target);
  53259. };
  53260. StopAnimationAction.prototype.serialize = function (parent) {
  53261. return _super.prototype._serialize.call(this, {
  53262. name: "StopAnimationAction",
  53263. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53264. }, parent);
  53265. };
  53266. return StopAnimationAction;
  53267. }(BABYLON.Action));
  53268. BABYLON.StopAnimationAction = StopAnimationAction;
  53269. var DoNothingAction = /** @class */ (function (_super) {
  53270. __extends(DoNothingAction, _super);
  53271. function DoNothingAction(triggerOptions, condition) {
  53272. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53273. return _super.call(this, triggerOptions, condition) || this;
  53274. }
  53275. DoNothingAction.prototype.execute = function () {
  53276. };
  53277. DoNothingAction.prototype.serialize = function (parent) {
  53278. return _super.prototype._serialize.call(this, {
  53279. name: "DoNothingAction",
  53280. properties: []
  53281. }, parent);
  53282. };
  53283. return DoNothingAction;
  53284. }(BABYLON.Action));
  53285. BABYLON.DoNothingAction = DoNothingAction;
  53286. var CombineAction = /** @class */ (function (_super) {
  53287. __extends(CombineAction, _super);
  53288. function CombineAction(triggerOptions, children, condition) {
  53289. var _this = _super.call(this, triggerOptions, condition) || this;
  53290. _this.children = children;
  53291. return _this;
  53292. }
  53293. CombineAction.prototype._prepare = function () {
  53294. for (var index = 0; index < this.children.length; index++) {
  53295. this.children[index]._actionManager = this._actionManager;
  53296. this.children[index]._prepare();
  53297. }
  53298. };
  53299. CombineAction.prototype.execute = function (evt) {
  53300. for (var index = 0; index < this.children.length; index++) {
  53301. this.children[index].execute(evt);
  53302. }
  53303. };
  53304. CombineAction.prototype.serialize = function (parent) {
  53305. var serializationObject = _super.prototype._serialize.call(this, {
  53306. name: "CombineAction",
  53307. properties: [],
  53308. combine: []
  53309. }, parent);
  53310. for (var i = 0; i < this.children.length; i++) {
  53311. serializationObject.combine.push(this.children[i].serialize(null));
  53312. }
  53313. return serializationObject;
  53314. };
  53315. return CombineAction;
  53316. }(BABYLON.Action));
  53317. BABYLON.CombineAction = CombineAction;
  53318. var ExecuteCodeAction = /** @class */ (function (_super) {
  53319. __extends(ExecuteCodeAction, _super);
  53320. function ExecuteCodeAction(triggerOptions, func, condition) {
  53321. var _this = _super.call(this, triggerOptions, condition) || this;
  53322. _this.func = func;
  53323. return _this;
  53324. }
  53325. ExecuteCodeAction.prototype.execute = function (evt) {
  53326. this.func(evt);
  53327. };
  53328. return ExecuteCodeAction;
  53329. }(BABYLON.Action));
  53330. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53331. var SetParentAction = /** @class */ (function (_super) {
  53332. __extends(SetParentAction, _super);
  53333. function SetParentAction(triggerOptions, target, parent, condition) {
  53334. var _this = _super.call(this, triggerOptions, condition) || this;
  53335. _this._target = target;
  53336. _this._parent = parent;
  53337. return _this;
  53338. }
  53339. SetParentAction.prototype._prepare = function () {
  53340. };
  53341. SetParentAction.prototype.execute = function () {
  53342. if (this._target.parent === this._parent) {
  53343. return;
  53344. }
  53345. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53346. invertParentWorldMatrix.invert();
  53347. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53348. this._target.parent = this._parent;
  53349. };
  53350. SetParentAction.prototype.serialize = function (parent) {
  53351. return _super.prototype._serialize.call(this, {
  53352. name: "SetParentAction",
  53353. properties: [
  53354. BABYLON.Action._GetTargetProperty(this._target),
  53355. BABYLON.Action._GetTargetProperty(this._parent),
  53356. ]
  53357. }, parent);
  53358. };
  53359. return SetParentAction;
  53360. }(BABYLON.Action));
  53361. BABYLON.SetParentAction = SetParentAction;
  53362. var PlaySoundAction = /** @class */ (function (_super) {
  53363. __extends(PlaySoundAction, _super);
  53364. function PlaySoundAction(triggerOptions, sound, condition) {
  53365. var _this = _super.call(this, triggerOptions, condition) || this;
  53366. _this._sound = sound;
  53367. return _this;
  53368. }
  53369. PlaySoundAction.prototype._prepare = function () {
  53370. };
  53371. PlaySoundAction.prototype.execute = function () {
  53372. if (this._sound !== undefined)
  53373. this._sound.play();
  53374. };
  53375. PlaySoundAction.prototype.serialize = function (parent) {
  53376. return _super.prototype._serialize.call(this, {
  53377. name: "PlaySoundAction",
  53378. properties: [{ name: "sound", value: this._sound.name }]
  53379. }, parent);
  53380. };
  53381. return PlaySoundAction;
  53382. }(BABYLON.Action));
  53383. BABYLON.PlaySoundAction = PlaySoundAction;
  53384. var StopSoundAction = /** @class */ (function (_super) {
  53385. __extends(StopSoundAction, _super);
  53386. function StopSoundAction(triggerOptions, sound, condition) {
  53387. var _this = _super.call(this, triggerOptions, condition) || this;
  53388. _this._sound = sound;
  53389. return _this;
  53390. }
  53391. StopSoundAction.prototype._prepare = function () {
  53392. };
  53393. StopSoundAction.prototype.execute = function () {
  53394. if (this._sound !== undefined)
  53395. this._sound.stop();
  53396. };
  53397. StopSoundAction.prototype.serialize = function (parent) {
  53398. return _super.prototype._serialize.call(this, {
  53399. name: "StopSoundAction",
  53400. properties: [{ name: "sound", value: this._sound.name }]
  53401. }, parent);
  53402. };
  53403. return StopSoundAction;
  53404. }(BABYLON.Action));
  53405. BABYLON.StopSoundAction = StopSoundAction;
  53406. })(BABYLON || (BABYLON = {}));
  53407. //# sourceMappingURL=babylon.directActions.js.map
  53408. var BABYLON;
  53409. (function (BABYLON) {
  53410. var SpriteManager = /** @class */ (function () {
  53411. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53412. if (epsilon === void 0) { epsilon = 0.01; }
  53413. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53414. this.name = name;
  53415. this.sprites = new Array();
  53416. this.renderingGroupId = 0;
  53417. this.layerMask = 0x0FFFFFFF;
  53418. this.fogEnabled = true;
  53419. this.isPickable = false;
  53420. /**
  53421. * An event triggered when the manager is disposed.
  53422. */
  53423. this.onDisposeObservable = new BABYLON.Observable();
  53424. this._vertexBuffers = {};
  53425. this._capacity = capacity;
  53426. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53427. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53428. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53429. if (cellSize.width && cellSize.height) {
  53430. this.cellWidth = cellSize.width;
  53431. this.cellHeight = cellSize.height;
  53432. }
  53433. else if (cellSize !== undefined) {
  53434. this.cellWidth = cellSize;
  53435. this.cellHeight = cellSize;
  53436. }
  53437. else {
  53438. return;
  53439. }
  53440. this._epsilon = epsilon;
  53441. this._scene = scene;
  53442. this._scene.spriteManagers.push(this);
  53443. var indices = [];
  53444. var index = 0;
  53445. for (var count = 0; count < capacity; count++) {
  53446. indices.push(index);
  53447. indices.push(index + 1);
  53448. indices.push(index + 2);
  53449. indices.push(index);
  53450. indices.push(index + 2);
  53451. indices.push(index + 3);
  53452. index += 4;
  53453. }
  53454. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53455. // VBO
  53456. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53457. this._vertexData = new Float32Array(capacity * 16 * 4);
  53458. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53459. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53460. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53461. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53462. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53463. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53464. this._vertexBuffers["options"] = options;
  53465. this._vertexBuffers["cellInfo"] = cellInfo;
  53466. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53467. // Effects
  53468. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53469. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53470. }
  53471. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53472. set: function (callback) {
  53473. if (this._onDisposeObserver) {
  53474. this.onDisposeObservable.remove(this._onDisposeObserver);
  53475. }
  53476. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53477. },
  53478. enumerable: true,
  53479. configurable: true
  53480. });
  53481. Object.defineProperty(SpriteManager.prototype, "texture", {
  53482. get: function () {
  53483. return this._spriteTexture;
  53484. },
  53485. set: function (value) {
  53486. this._spriteTexture = value;
  53487. },
  53488. enumerable: true,
  53489. configurable: true
  53490. });
  53491. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53492. var arrayOffset = index * 16;
  53493. if (offsetX === 0)
  53494. offsetX = this._epsilon;
  53495. else if (offsetX === 1)
  53496. offsetX = 1 - this._epsilon;
  53497. if (offsetY === 0)
  53498. offsetY = this._epsilon;
  53499. else if (offsetY === 1)
  53500. offsetY = 1 - this._epsilon;
  53501. this._vertexData[arrayOffset] = sprite.position.x;
  53502. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53503. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53504. this._vertexData[arrayOffset + 3] = sprite.angle;
  53505. this._vertexData[arrayOffset + 4] = sprite.width;
  53506. this._vertexData[arrayOffset + 5] = sprite.height;
  53507. this._vertexData[arrayOffset + 6] = offsetX;
  53508. this._vertexData[arrayOffset + 7] = offsetY;
  53509. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53510. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53511. var offset = (sprite.cellIndex / rowSize) >> 0;
  53512. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53513. this._vertexData[arrayOffset + 11] = offset;
  53514. // Color
  53515. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53516. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53517. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53518. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53519. };
  53520. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53521. var count = Math.min(this._capacity, this.sprites.length);
  53522. var min = BABYLON.Vector3.Zero();
  53523. var max = BABYLON.Vector3.Zero();
  53524. var distance = Number.MAX_VALUE;
  53525. var currentSprite = null;
  53526. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53527. var cameraView = camera.getViewMatrix();
  53528. for (var index = 0; index < count; index++) {
  53529. var sprite = this.sprites[index];
  53530. if (!sprite) {
  53531. continue;
  53532. }
  53533. if (predicate) {
  53534. if (!predicate(sprite)) {
  53535. continue;
  53536. }
  53537. }
  53538. else if (!sprite.isPickable) {
  53539. continue;
  53540. }
  53541. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53542. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53543. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53544. if (ray.intersectsBoxMinMax(min, max)) {
  53545. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53546. if (distance > currentDistance) {
  53547. distance = currentDistance;
  53548. currentSprite = sprite;
  53549. if (fastCheck) {
  53550. break;
  53551. }
  53552. }
  53553. }
  53554. }
  53555. if (currentSprite) {
  53556. var result = new BABYLON.PickingInfo();
  53557. result.hit = true;
  53558. result.pickedSprite = currentSprite;
  53559. result.distance = distance;
  53560. return result;
  53561. }
  53562. return null;
  53563. };
  53564. SpriteManager.prototype.render = function () {
  53565. // Check
  53566. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53567. return;
  53568. var engine = this._scene.getEngine();
  53569. var baseSize = this._spriteTexture.getBaseSize();
  53570. // Sprites
  53571. var deltaTime = engine.getDeltaTime();
  53572. var max = Math.min(this._capacity, this.sprites.length);
  53573. var rowSize = baseSize.width / this.cellWidth;
  53574. var offset = 0;
  53575. for (var index = 0; index < max; index++) {
  53576. var sprite = this.sprites[index];
  53577. if (!sprite || !sprite.isVisible) {
  53578. continue;
  53579. }
  53580. sprite._animate(deltaTime);
  53581. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53582. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53583. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53584. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53585. }
  53586. this._buffer.update(this._vertexData);
  53587. // Render
  53588. var effect = this._effectBase;
  53589. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53590. effect = this._effectFog;
  53591. }
  53592. engine.enableEffect(effect);
  53593. var viewMatrix = this._scene.getViewMatrix();
  53594. effect.setTexture("diffuseSampler", this._spriteTexture);
  53595. effect.setMatrix("view", viewMatrix);
  53596. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53597. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53598. // Fog
  53599. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53600. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53601. effect.setColor3("vFogColor", this._scene.fogColor);
  53602. }
  53603. // VBOs
  53604. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53605. // Draw order
  53606. engine.setDepthFunctionToLessOrEqual();
  53607. effect.setBool("alphaTest", true);
  53608. engine.setColorWrite(false);
  53609. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53610. engine.setColorWrite(true);
  53611. effect.setBool("alphaTest", false);
  53612. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53613. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53614. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53615. };
  53616. SpriteManager.prototype.dispose = function () {
  53617. if (this._buffer) {
  53618. this._buffer.dispose();
  53619. this._buffer = null;
  53620. }
  53621. if (this._indexBuffer) {
  53622. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53623. this._indexBuffer = null;
  53624. }
  53625. if (this._spriteTexture) {
  53626. this._spriteTexture.dispose();
  53627. this._spriteTexture = null;
  53628. }
  53629. // Remove from scene
  53630. var index = this._scene.spriteManagers.indexOf(this);
  53631. this._scene.spriteManagers.splice(index, 1);
  53632. // Callback
  53633. this.onDisposeObservable.notifyObservers(this);
  53634. this.onDisposeObservable.clear();
  53635. };
  53636. return SpriteManager;
  53637. }());
  53638. BABYLON.SpriteManager = SpriteManager;
  53639. })(BABYLON || (BABYLON = {}));
  53640. //# sourceMappingURL=babylon.spriteManager.js.map
  53641. var BABYLON;
  53642. (function (BABYLON) {
  53643. var Sprite = /** @class */ (function () {
  53644. function Sprite(name, manager) {
  53645. this.name = name;
  53646. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53647. this.width = 1.0;
  53648. this.height = 1.0;
  53649. this.angle = 0;
  53650. this.cellIndex = 0;
  53651. this.invertU = 0;
  53652. this.invertV = 0;
  53653. this.animations = new Array();
  53654. this.isPickable = false;
  53655. this._animationStarted = false;
  53656. this._loopAnimation = false;
  53657. this._fromIndex = 0;
  53658. this._toIndex = 0;
  53659. this._delay = 0;
  53660. this._direction = 1;
  53661. this._time = 0;
  53662. /**
  53663. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53664. */
  53665. this.isVisible = true;
  53666. this._manager = manager;
  53667. this._manager.sprites.push(this);
  53668. this.position = BABYLON.Vector3.Zero();
  53669. }
  53670. Object.defineProperty(Sprite.prototype, "size", {
  53671. get: function () {
  53672. return this.width;
  53673. },
  53674. set: function (value) {
  53675. this.width = value;
  53676. this.height = value;
  53677. },
  53678. enumerable: true,
  53679. configurable: true
  53680. });
  53681. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53682. this._fromIndex = from;
  53683. this._toIndex = to;
  53684. this._loopAnimation = loop;
  53685. this._delay = delay;
  53686. this._animationStarted = true;
  53687. this._direction = from < to ? 1 : -1;
  53688. this.cellIndex = from;
  53689. this._time = 0;
  53690. this._onAnimationEnd = onAnimationEnd;
  53691. };
  53692. Sprite.prototype.stopAnimation = function () {
  53693. this._animationStarted = false;
  53694. };
  53695. Sprite.prototype._animate = function (deltaTime) {
  53696. if (!this._animationStarted)
  53697. return;
  53698. this._time += deltaTime;
  53699. if (this._time > this._delay) {
  53700. this._time = this._time % this._delay;
  53701. this.cellIndex += this._direction;
  53702. if (this.cellIndex > this._toIndex) {
  53703. if (this._loopAnimation) {
  53704. this.cellIndex = this._fromIndex;
  53705. }
  53706. else {
  53707. this.cellIndex = this._toIndex;
  53708. this._animationStarted = false;
  53709. if (this._onAnimationEnd) {
  53710. this._onAnimationEnd();
  53711. }
  53712. if (this.disposeWhenFinishedAnimating) {
  53713. this.dispose();
  53714. }
  53715. }
  53716. }
  53717. }
  53718. };
  53719. Sprite.prototype.dispose = function () {
  53720. for (var i = 0; i < this._manager.sprites.length; i++) {
  53721. if (this._manager.sprites[i] == this) {
  53722. this._manager.sprites.splice(i, 1);
  53723. }
  53724. }
  53725. };
  53726. return Sprite;
  53727. }());
  53728. BABYLON.Sprite = Sprite;
  53729. })(BABYLON || (BABYLON = {}));
  53730. //# sourceMappingURL=babylon.sprite.js.map
  53731. var BABYLON;
  53732. (function (BABYLON) {
  53733. var IntersectionInfo = /** @class */ (function () {
  53734. function IntersectionInfo(bu, bv, distance) {
  53735. this.bu = bu;
  53736. this.bv = bv;
  53737. this.distance = distance;
  53738. this.faceId = 0;
  53739. this.subMeshId = 0;
  53740. }
  53741. return IntersectionInfo;
  53742. }());
  53743. BABYLON.IntersectionInfo = IntersectionInfo;
  53744. /**
  53745. * Information about the result of picking within a scene
  53746. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53747. */
  53748. var PickingInfo = /** @class */ (function () {
  53749. function PickingInfo() {
  53750. /**
  53751. * If the pick collided with an object
  53752. */
  53753. this.hit = false;
  53754. /**
  53755. * Distance away where the pick collided
  53756. */
  53757. this.distance = 0;
  53758. /**
  53759. * The location of pick collision
  53760. */
  53761. this.pickedPoint = null;
  53762. /**
  53763. * The mesh corrisponding the the pick collision
  53764. */
  53765. this.pickedMesh = null;
  53766. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53767. this.bu = 0;
  53768. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53769. this.bv = 0;
  53770. /** The id of the face on the mesh that was picked */
  53771. this.faceId = -1;
  53772. /** Id of the the submesh that was picked */
  53773. this.subMeshId = 0;
  53774. /** If a sprite was picked, this will be the sprite the pick collided with */
  53775. this.pickedSprite = null;
  53776. /**
  53777. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53778. */
  53779. this.originMesh = null;
  53780. /**
  53781. * The ray that was used to perform the picking.
  53782. */
  53783. this.ray = null;
  53784. }
  53785. /**
  53786. * Gets the normal corrispodning to the face the pick collided with
  53787. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53788. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53789. * @returns The normal corrispodning to the face the pick collided with
  53790. */
  53791. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53792. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53793. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53794. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53795. return null;
  53796. }
  53797. var indices = this.pickedMesh.getIndices();
  53798. if (!indices) {
  53799. return null;
  53800. }
  53801. var result;
  53802. if (useVerticesNormals) {
  53803. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53804. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53805. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53806. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53807. normal0 = normal0.scale(this.bu);
  53808. normal1 = normal1.scale(this.bv);
  53809. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53810. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53811. }
  53812. else {
  53813. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53814. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53815. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53816. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53817. var p1p2 = vertex1.subtract(vertex2);
  53818. var p3p2 = vertex3.subtract(vertex2);
  53819. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53820. }
  53821. if (useWorldCoordinates) {
  53822. var wm = this.pickedMesh.getWorldMatrix();
  53823. if (this.pickedMesh.nonUniformScaling) {
  53824. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53825. wm = BABYLON.Tmp.Matrix[0];
  53826. wm.setTranslationFromFloats(0, 0, 0);
  53827. wm.invert();
  53828. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53829. wm = BABYLON.Tmp.Matrix[1];
  53830. }
  53831. result = BABYLON.Vector3.TransformNormal(result, wm);
  53832. }
  53833. result.normalize();
  53834. return result;
  53835. };
  53836. /**
  53837. * Gets the texture coordinates of where the pick occured
  53838. * @returns the vector containing the coordnates of the texture
  53839. */
  53840. PickingInfo.prototype.getTextureCoordinates = function () {
  53841. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53842. return null;
  53843. }
  53844. var indices = this.pickedMesh.getIndices();
  53845. if (!indices) {
  53846. return null;
  53847. }
  53848. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53849. if (!uvs) {
  53850. return null;
  53851. }
  53852. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53853. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53854. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53855. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53856. uv1 = uv1.scale(this.bu);
  53857. uv2 = uv2.scale(this.bv);
  53858. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53859. };
  53860. return PickingInfo;
  53861. }());
  53862. BABYLON.PickingInfo = PickingInfo;
  53863. })(BABYLON || (BABYLON = {}));
  53864. //# sourceMappingURL=babylon.pickingInfo.js.map
  53865. var BABYLON;
  53866. (function (BABYLON) {
  53867. var Ray = /** @class */ (function () {
  53868. function Ray(origin, direction, length) {
  53869. if (length === void 0) { length = Number.MAX_VALUE; }
  53870. this.origin = origin;
  53871. this.direction = direction;
  53872. this.length = length;
  53873. }
  53874. // Methods
  53875. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53876. var d = 0.0;
  53877. var maxValue = Number.MAX_VALUE;
  53878. var inv;
  53879. var min;
  53880. var max;
  53881. var temp;
  53882. if (Math.abs(this.direction.x) < 0.0000001) {
  53883. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53884. return false;
  53885. }
  53886. }
  53887. else {
  53888. inv = 1.0 / this.direction.x;
  53889. min = (minimum.x - this.origin.x) * inv;
  53890. max = (maximum.x - this.origin.x) * inv;
  53891. if (max === -Infinity) {
  53892. max = Infinity;
  53893. }
  53894. if (min > max) {
  53895. temp = min;
  53896. min = max;
  53897. max = temp;
  53898. }
  53899. d = Math.max(min, d);
  53900. maxValue = Math.min(max, maxValue);
  53901. if (d > maxValue) {
  53902. return false;
  53903. }
  53904. }
  53905. if (Math.abs(this.direction.y) < 0.0000001) {
  53906. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53907. return false;
  53908. }
  53909. }
  53910. else {
  53911. inv = 1.0 / this.direction.y;
  53912. min = (minimum.y - this.origin.y) * inv;
  53913. max = (maximum.y - this.origin.y) * inv;
  53914. if (max === -Infinity) {
  53915. max = Infinity;
  53916. }
  53917. if (min > max) {
  53918. temp = min;
  53919. min = max;
  53920. max = temp;
  53921. }
  53922. d = Math.max(min, d);
  53923. maxValue = Math.min(max, maxValue);
  53924. if (d > maxValue) {
  53925. return false;
  53926. }
  53927. }
  53928. if (Math.abs(this.direction.z) < 0.0000001) {
  53929. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53930. return false;
  53931. }
  53932. }
  53933. else {
  53934. inv = 1.0 / this.direction.z;
  53935. min = (minimum.z - this.origin.z) * inv;
  53936. max = (maximum.z - this.origin.z) * inv;
  53937. if (max === -Infinity) {
  53938. max = Infinity;
  53939. }
  53940. if (min > max) {
  53941. temp = min;
  53942. min = max;
  53943. max = temp;
  53944. }
  53945. d = Math.max(min, d);
  53946. maxValue = Math.min(max, maxValue);
  53947. if (d > maxValue) {
  53948. return false;
  53949. }
  53950. }
  53951. return true;
  53952. };
  53953. Ray.prototype.intersectsBox = function (box) {
  53954. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53955. };
  53956. Ray.prototype.intersectsSphere = function (sphere) {
  53957. var x = sphere.center.x - this.origin.x;
  53958. var y = sphere.center.y - this.origin.y;
  53959. var z = sphere.center.z - this.origin.z;
  53960. var pyth = (x * x) + (y * y) + (z * z);
  53961. var rr = sphere.radius * sphere.radius;
  53962. if (pyth <= rr) {
  53963. return true;
  53964. }
  53965. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53966. if (dot < 0.0) {
  53967. return false;
  53968. }
  53969. var temp = pyth - (dot * dot);
  53970. return temp <= rr;
  53971. };
  53972. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53973. if (!this._edge1) {
  53974. this._edge1 = BABYLON.Vector3.Zero();
  53975. this._edge2 = BABYLON.Vector3.Zero();
  53976. this._pvec = BABYLON.Vector3.Zero();
  53977. this._tvec = BABYLON.Vector3.Zero();
  53978. this._qvec = BABYLON.Vector3.Zero();
  53979. }
  53980. vertex1.subtractToRef(vertex0, this._edge1);
  53981. vertex2.subtractToRef(vertex0, this._edge2);
  53982. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53983. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53984. if (det === 0) {
  53985. return null;
  53986. }
  53987. var invdet = 1 / det;
  53988. this.origin.subtractToRef(vertex0, this._tvec);
  53989. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53990. if (bu < 0 || bu > 1.0) {
  53991. return null;
  53992. }
  53993. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53994. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53995. if (bv < 0 || bu + bv > 1.0) {
  53996. return null;
  53997. }
  53998. //check if the distance is longer than the predefined length.
  53999. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54000. if (distance > this.length) {
  54001. return null;
  54002. }
  54003. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54004. };
  54005. Ray.prototype.intersectsPlane = function (plane) {
  54006. var distance;
  54007. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54008. if (Math.abs(result1) < 9.99999997475243E-07) {
  54009. return null;
  54010. }
  54011. else {
  54012. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54013. distance = (-plane.d - result2) / result1;
  54014. if (distance < 0.0) {
  54015. if (distance < -9.99999997475243E-07) {
  54016. return null;
  54017. }
  54018. else {
  54019. return 0;
  54020. }
  54021. }
  54022. return distance;
  54023. }
  54024. };
  54025. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54026. var tm = BABYLON.Tmp.Matrix[0];
  54027. mesh.getWorldMatrix().invertToRef(tm);
  54028. if (this._tmpRay) {
  54029. Ray.TransformToRef(this, tm, this._tmpRay);
  54030. }
  54031. else {
  54032. this._tmpRay = Ray.Transform(this, tm);
  54033. }
  54034. return mesh.intersects(this._tmpRay, fastCheck);
  54035. };
  54036. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54037. if (results) {
  54038. results.length = 0;
  54039. }
  54040. else {
  54041. results = [];
  54042. }
  54043. for (var i = 0; i < meshes.length; i++) {
  54044. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54045. if (pickInfo.hit) {
  54046. results.push(pickInfo);
  54047. }
  54048. }
  54049. results.sort(this._comparePickingInfo);
  54050. return results;
  54051. };
  54052. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54053. if (pickingInfoA.distance < pickingInfoB.distance) {
  54054. return -1;
  54055. }
  54056. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54057. return 1;
  54058. }
  54059. else {
  54060. return 0;
  54061. }
  54062. };
  54063. /**
  54064. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54065. * @param sega the first point of the segment to test the intersection against
  54066. * @param segb the second point of the segment to test the intersection against
  54067. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54068. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54069. */
  54070. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54071. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54072. var u = segb.subtract(sega);
  54073. var v = rsegb.subtract(this.origin);
  54074. var w = sega.subtract(this.origin);
  54075. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54076. var b = BABYLON.Vector3.Dot(u, v);
  54077. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54078. var d = BABYLON.Vector3.Dot(u, w);
  54079. var e = BABYLON.Vector3.Dot(v, w);
  54080. var D = a * c - b * b; // always >= 0
  54081. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54082. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54083. // compute the line parameters of the two closest points
  54084. if (D < Ray.smallnum) { // the lines are almost parallel
  54085. sN = 0.0; // force using point P0 on segment S1
  54086. sD = 1.0; // to prevent possible division by 0.0 later
  54087. tN = e;
  54088. tD = c;
  54089. }
  54090. else { // get the closest points on the infinite lines
  54091. sN = (b * e - c * d);
  54092. tN = (a * e - b * d);
  54093. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54094. sN = 0.0;
  54095. tN = e;
  54096. tD = c;
  54097. }
  54098. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54099. sN = sD;
  54100. tN = e + b;
  54101. tD = c;
  54102. }
  54103. }
  54104. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54105. tN = 0.0;
  54106. // recompute sc for this edge
  54107. if (-d < 0.0) {
  54108. sN = 0.0;
  54109. }
  54110. else if (-d > a)
  54111. sN = sD;
  54112. else {
  54113. sN = -d;
  54114. sD = a;
  54115. }
  54116. }
  54117. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54118. tN = tD;
  54119. // recompute sc for this edge
  54120. if ((-d + b) < 0.0) {
  54121. sN = 0;
  54122. }
  54123. else if ((-d + b) > a) {
  54124. sN = sD;
  54125. }
  54126. else {
  54127. sN = (-d + b);
  54128. sD = a;
  54129. }
  54130. }
  54131. // finally do the division to get sc and tc
  54132. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54133. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54134. // get the difference of the two closest points
  54135. var qtc = v.multiplyByFloats(tc, tc, tc);
  54136. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54137. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54138. if (isIntersected) {
  54139. return qtc.length();
  54140. }
  54141. return -1;
  54142. };
  54143. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54144. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54145. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54146. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54147. this.direction.normalize();
  54148. return this;
  54149. };
  54150. // Statics
  54151. Ray.Zero = function () {
  54152. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54153. };
  54154. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54155. var result = Ray.Zero();
  54156. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54157. };
  54158. /**
  54159. * 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
  54160. * transformed to the given world matrix.
  54161. * @param origin The origin point
  54162. * @param end The end point
  54163. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54164. */
  54165. Ray.CreateNewFromTo = function (origin, end, world) {
  54166. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54167. var direction = end.subtract(origin);
  54168. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54169. direction.normalize();
  54170. return Ray.Transform(new Ray(origin, direction, length), world);
  54171. };
  54172. Ray.Transform = function (ray, matrix) {
  54173. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54174. Ray.TransformToRef(ray, matrix, result);
  54175. return result;
  54176. };
  54177. Ray.TransformToRef = function (ray, matrix, result) {
  54178. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54179. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54180. result.length = ray.length;
  54181. var dir = result.direction;
  54182. var len = dir.length();
  54183. if (!(len === 0 || len === 1)) {
  54184. var num = 1.0 / len;
  54185. dir.x *= num;
  54186. dir.y *= num;
  54187. dir.z *= num;
  54188. result.length *= len;
  54189. }
  54190. };
  54191. Ray.smallnum = 0.00000001;
  54192. Ray.rayl = 10e8;
  54193. return Ray;
  54194. }());
  54195. BABYLON.Ray = Ray;
  54196. })(BABYLON || (BABYLON = {}));
  54197. //# sourceMappingURL=babylon.ray.js.map
  54198. var BABYLON;
  54199. (function (BABYLON) {
  54200. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54201. if (boxMin.x > sphereCenter.x + sphereRadius)
  54202. return false;
  54203. if (sphereCenter.x - sphereRadius > boxMax.x)
  54204. return false;
  54205. if (boxMin.y > sphereCenter.y + sphereRadius)
  54206. return false;
  54207. if (sphereCenter.y - sphereRadius > boxMax.y)
  54208. return false;
  54209. if (boxMin.z > sphereCenter.z + sphereRadius)
  54210. return false;
  54211. if (sphereCenter.z - sphereRadius > boxMax.z)
  54212. return false;
  54213. return true;
  54214. };
  54215. var getLowestRoot = (function () {
  54216. var result = { root: 0, found: false };
  54217. return function (a, b, c, maxR) {
  54218. result.root = 0;
  54219. result.found = false;
  54220. var determinant = b * b - 4.0 * a * c;
  54221. if (determinant < 0)
  54222. return result;
  54223. var sqrtD = Math.sqrt(determinant);
  54224. var r1 = (-b - sqrtD) / (2.0 * a);
  54225. var r2 = (-b + sqrtD) / (2.0 * a);
  54226. if (r1 > r2) {
  54227. var temp = r2;
  54228. r2 = r1;
  54229. r1 = temp;
  54230. }
  54231. if (r1 > 0 && r1 < maxR) {
  54232. result.root = r1;
  54233. result.found = true;
  54234. return result;
  54235. }
  54236. if (r2 > 0 && r2 < maxR) {
  54237. result.root = r2;
  54238. result.found = true;
  54239. return result;
  54240. }
  54241. return result;
  54242. };
  54243. })();
  54244. var Collider = /** @class */ (function () {
  54245. function Collider() {
  54246. this._collisionPoint = BABYLON.Vector3.Zero();
  54247. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54248. this._tempVector = BABYLON.Vector3.Zero();
  54249. this._tempVector2 = BABYLON.Vector3.Zero();
  54250. this._tempVector3 = BABYLON.Vector3.Zero();
  54251. this._tempVector4 = BABYLON.Vector3.Zero();
  54252. this._edge = BABYLON.Vector3.Zero();
  54253. this._baseToVertex = BABYLON.Vector3.Zero();
  54254. this._destinationPoint = BABYLON.Vector3.Zero();
  54255. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54256. this._displacementVector = BABYLON.Vector3.Zero();
  54257. this._radius = BABYLON.Vector3.One();
  54258. this._retry = 0;
  54259. this._basePointWorld = BABYLON.Vector3.Zero();
  54260. this._velocityWorld = BABYLON.Vector3.Zero();
  54261. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54262. this._collisionMask = -1;
  54263. }
  54264. Object.defineProperty(Collider.prototype, "collisionMask", {
  54265. get: function () {
  54266. return this._collisionMask;
  54267. },
  54268. set: function (mask) {
  54269. this._collisionMask = !isNaN(mask) ? mask : -1;
  54270. },
  54271. enumerable: true,
  54272. configurable: true
  54273. });
  54274. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54275. /**
  54276. * Gets the plane normal used to compute the sliding response (in local space)
  54277. */
  54278. get: function () {
  54279. return this._slidePlaneNormal;
  54280. },
  54281. enumerable: true,
  54282. configurable: true
  54283. });
  54284. // Methods
  54285. Collider.prototype._initialize = function (source, dir, e) {
  54286. this._velocity = dir;
  54287. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54288. this._basePoint = source;
  54289. source.multiplyToRef(this._radius, this._basePointWorld);
  54290. dir.multiplyToRef(this._radius, this._velocityWorld);
  54291. this._velocityWorldLength = this._velocityWorld.length();
  54292. this._epsilon = e;
  54293. this.collisionFound = false;
  54294. };
  54295. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54296. pa.subtractToRef(point, this._tempVector);
  54297. pb.subtractToRef(point, this._tempVector2);
  54298. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54299. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54300. if (d < 0)
  54301. return false;
  54302. pc.subtractToRef(point, this._tempVector3);
  54303. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54304. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54305. if (d < 0)
  54306. return false;
  54307. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54308. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54309. return d >= 0;
  54310. };
  54311. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54312. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54313. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54314. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54315. return false;
  54316. }
  54317. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54318. return false;
  54319. return true;
  54320. };
  54321. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54322. var t0;
  54323. var embeddedInPlane = false;
  54324. //defensive programming, actually not needed.
  54325. if (!trianglePlaneArray) {
  54326. trianglePlaneArray = [];
  54327. }
  54328. if (!trianglePlaneArray[faceIndex]) {
  54329. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54330. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54331. }
  54332. var trianglePlane = trianglePlaneArray[faceIndex];
  54333. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54334. return;
  54335. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54336. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54337. if (normalDotVelocity == 0) {
  54338. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54339. return;
  54340. embeddedInPlane = true;
  54341. t0 = 0;
  54342. }
  54343. else {
  54344. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54345. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54346. if (t0 > t1) {
  54347. var temp = t1;
  54348. t1 = t0;
  54349. t0 = temp;
  54350. }
  54351. if (t0 > 1.0 || t1 < 0.0)
  54352. return;
  54353. if (t0 < 0)
  54354. t0 = 0;
  54355. if (t0 > 1.0)
  54356. t0 = 1.0;
  54357. }
  54358. this._collisionPoint.copyFromFloats(0, 0, 0);
  54359. var found = false;
  54360. var t = 1.0;
  54361. if (!embeddedInPlane) {
  54362. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54363. this._velocity.scaleToRef(t0, this._tempVector);
  54364. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54365. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54366. found = true;
  54367. t = t0;
  54368. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54369. }
  54370. }
  54371. if (!found) {
  54372. var velocitySquaredLength = this._velocity.lengthSquared();
  54373. var a = velocitySquaredLength;
  54374. this._basePoint.subtractToRef(p1, this._tempVector);
  54375. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54376. var c = this._tempVector.lengthSquared() - 1.0;
  54377. var lowestRoot = getLowestRoot(a, b, c, t);
  54378. if (lowestRoot.found) {
  54379. t = lowestRoot.root;
  54380. found = true;
  54381. this._collisionPoint.copyFrom(p1);
  54382. }
  54383. this._basePoint.subtractToRef(p2, this._tempVector);
  54384. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54385. c = this._tempVector.lengthSquared() - 1.0;
  54386. lowestRoot = getLowestRoot(a, b, c, t);
  54387. if (lowestRoot.found) {
  54388. t = lowestRoot.root;
  54389. found = true;
  54390. this._collisionPoint.copyFrom(p2);
  54391. }
  54392. this._basePoint.subtractToRef(p3, this._tempVector);
  54393. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54394. c = this._tempVector.lengthSquared() - 1.0;
  54395. lowestRoot = getLowestRoot(a, b, c, t);
  54396. if (lowestRoot.found) {
  54397. t = lowestRoot.root;
  54398. found = true;
  54399. this._collisionPoint.copyFrom(p3);
  54400. }
  54401. p2.subtractToRef(p1, this._edge);
  54402. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54403. var edgeSquaredLength = this._edge.lengthSquared();
  54404. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54405. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54406. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54407. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54408. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54409. lowestRoot = getLowestRoot(a, b, c, t);
  54410. if (lowestRoot.found) {
  54411. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54412. if (f >= 0.0 && f <= 1.0) {
  54413. t = lowestRoot.root;
  54414. found = true;
  54415. this._edge.scaleInPlace(f);
  54416. p1.addToRef(this._edge, this._collisionPoint);
  54417. }
  54418. }
  54419. p3.subtractToRef(p2, this._edge);
  54420. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54421. edgeSquaredLength = this._edge.lengthSquared();
  54422. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54423. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54424. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54425. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54426. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54427. lowestRoot = getLowestRoot(a, b, c, t);
  54428. if (lowestRoot.found) {
  54429. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54430. if (f >= 0.0 && f <= 1.0) {
  54431. t = lowestRoot.root;
  54432. found = true;
  54433. this._edge.scaleInPlace(f);
  54434. p2.addToRef(this._edge, this._collisionPoint);
  54435. }
  54436. }
  54437. p1.subtractToRef(p3, this._edge);
  54438. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54439. edgeSquaredLength = this._edge.lengthSquared();
  54440. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54441. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54442. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54443. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54444. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54445. lowestRoot = getLowestRoot(a, b, c, t);
  54446. if (lowestRoot.found) {
  54447. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54448. if (f >= 0.0 && f <= 1.0) {
  54449. t = lowestRoot.root;
  54450. found = true;
  54451. this._edge.scaleInPlace(f);
  54452. p3.addToRef(this._edge, this._collisionPoint);
  54453. }
  54454. }
  54455. }
  54456. if (found) {
  54457. var distToCollision = t * this._velocity.length();
  54458. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54459. if (!this.intersectionPoint) {
  54460. this.intersectionPoint = this._collisionPoint.clone();
  54461. }
  54462. else {
  54463. this.intersectionPoint.copyFrom(this._collisionPoint);
  54464. }
  54465. this._nearestDistance = distToCollision;
  54466. this.collisionFound = true;
  54467. }
  54468. }
  54469. };
  54470. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54471. for (var i = indexStart; i < indexEnd; i += 3) {
  54472. var p1 = pts[indices[i] - decal];
  54473. var p2 = pts[indices[i + 1] - decal];
  54474. var p3 = pts[indices[i + 2] - decal];
  54475. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54476. }
  54477. };
  54478. Collider.prototype._getResponse = function (pos, vel) {
  54479. pos.addToRef(vel, this._destinationPoint);
  54480. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54481. this._basePoint.addToRef(vel, pos);
  54482. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54483. this._slidePlaneNormal.normalize();
  54484. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54485. pos.addInPlace(this._displacementVector);
  54486. this.intersectionPoint.addInPlace(this._displacementVector);
  54487. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54488. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54489. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54490. };
  54491. return Collider;
  54492. }());
  54493. BABYLON.Collider = Collider;
  54494. })(BABYLON || (BABYLON = {}));
  54495. //# sourceMappingURL=babylon.collider.js.map
  54496. var BABYLON;
  54497. (function (BABYLON) {
  54498. //WebWorker code will be inserted to this variable.
  54499. BABYLON.CollisionWorker = "";
  54500. /** Defines supported task for worker process */
  54501. var WorkerTaskType;
  54502. (function (WorkerTaskType) {
  54503. /** Initialization */
  54504. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54505. /** Update of geometry */
  54506. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54507. /** Evaluate collision */
  54508. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54509. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54510. /** Defines kind of replies returned by worker */
  54511. var WorkerReplyType;
  54512. (function (WorkerReplyType) {
  54513. /** Success */
  54514. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54515. /** Unkown error */
  54516. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54517. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54518. var CollisionCoordinatorWorker = /** @class */ (function () {
  54519. function CollisionCoordinatorWorker() {
  54520. var _this = this;
  54521. this._scaledPosition = BABYLON.Vector3.Zero();
  54522. this._scaledVelocity = BABYLON.Vector3.Zero();
  54523. this.onMeshUpdated = function (transformNode) {
  54524. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54525. };
  54526. this.onGeometryUpdated = function (geometry) {
  54527. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54528. };
  54529. this._afterRender = function () {
  54530. if (!_this._init)
  54531. return;
  54532. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54533. return;
  54534. }
  54535. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54536. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54537. if (_this._runningUpdated > 4) {
  54538. return;
  54539. }
  54540. ++_this._runningUpdated;
  54541. var payload = {
  54542. updatedMeshes: _this._addUpdateMeshesList,
  54543. updatedGeometries: _this._addUpdateGeometriesList,
  54544. removedGeometries: _this._toRemoveGeometryArray,
  54545. removedMeshes: _this._toRemoveMeshesArray
  54546. };
  54547. var message = {
  54548. payload: payload,
  54549. taskType: WorkerTaskType.UPDATE
  54550. };
  54551. var serializable = [];
  54552. for (var id in payload.updatedGeometries) {
  54553. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54554. //prepare transferables
  54555. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54556. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54557. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54558. }
  54559. }
  54560. _this._worker.postMessage(message, serializable);
  54561. _this._addUpdateMeshesList = {};
  54562. _this._addUpdateGeometriesList = {};
  54563. _this._toRemoveGeometryArray = [];
  54564. _this._toRemoveMeshesArray = [];
  54565. };
  54566. this._onMessageFromWorker = function (e) {
  54567. var returnData = e.data;
  54568. if (returnData.error != WorkerReplyType.SUCCESS) {
  54569. //TODO what errors can be returned from the worker?
  54570. BABYLON.Tools.Warn("error returned from worker!");
  54571. return;
  54572. }
  54573. switch (returnData.taskType) {
  54574. case WorkerTaskType.INIT:
  54575. _this._init = true;
  54576. //Update the worked with ALL of the scene's current state
  54577. _this._scene.meshes.forEach(function (mesh) {
  54578. _this.onMeshAdded(mesh);
  54579. });
  54580. _this._scene.getGeometries().forEach(function (geometry) {
  54581. _this.onGeometryAdded(geometry);
  54582. });
  54583. break;
  54584. case WorkerTaskType.UPDATE:
  54585. _this._runningUpdated--;
  54586. break;
  54587. case WorkerTaskType.COLLIDE:
  54588. var returnPayload = returnData.payload;
  54589. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54590. return;
  54591. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54592. if (callback) {
  54593. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54594. if (mesh) {
  54595. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54596. }
  54597. }
  54598. //cleanup
  54599. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54600. break;
  54601. }
  54602. };
  54603. this._collisionsCallbackArray = [];
  54604. this._init = false;
  54605. this._runningUpdated = 0;
  54606. this._addUpdateMeshesList = {};
  54607. this._addUpdateGeometriesList = {};
  54608. this._toRemoveGeometryArray = [];
  54609. this._toRemoveMeshesArray = [];
  54610. }
  54611. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54612. if (!this._init)
  54613. return;
  54614. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54615. return;
  54616. position.divideToRef(collider._radius, this._scaledPosition);
  54617. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54618. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54619. var payload = {
  54620. collider: {
  54621. position: this._scaledPosition.asArray(),
  54622. velocity: this._scaledVelocity.asArray(),
  54623. radius: collider._radius.asArray()
  54624. },
  54625. collisionId: collisionIndex,
  54626. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54627. maximumRetry: maximumRetry
  54628. };
  54629. var message = {
  54630. payload: payload,
  54631. taskType: WorkerTaskType.COLLIDE
  54632. };
  54633. this._worker.postMessage(message);
  54634. };
  54635. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54636. this._scene = scene;
  54637. this._scene.registerAfterRender(this._afterRender);
  54638. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54639. this._worker = new Worker(workerUrl);
  54640. this._worker.onmessage = this._onMessageFromWorker;
  54641. var message = {
  54642. payload: {},
  54643. taskType: WorkerTaskType.INIT
  54644. };
  54645. this._worker.postMessage(message);
  54646. };
  54647. CollisionCoordinatorWorker.prototype.destroy = function () {
  54648. this._scene.unregisterAfterRender(this._afterRender);
  54649. this._worker.terminate();
  54650. };
  54651. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54652. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54653. this.onMeshUpdated(mesh);
  54654. };
  54655. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54656. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54657. };
  54658. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54659. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54660. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54661. this.onGeometryUpdated(geometry);
  54662. };
  54663. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54664. this._toRemoveGeometryArray.push(geometry.id);
  54665. };
  54666. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54667. var submeshes = [];
  54668. if (mesh.subMeshes) {
  54669. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54670. var boundingInfo = sm.getBoundingInfo();
  54671. return {
  54672. position: idx,
  54673. verticesStart: sm.verticesStart,
  54674. verticesCount: sm.verticesCount,
  54675. indexStart: sm.indexStart,
  54676. indexCount: sm.indexCount,
  54677. hasMaterial: !!sm.getMaterial(),
  54678. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54679. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54680. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54681. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54682. };
  54683. });
  54684. }
  54685. var geometryId = null;
  54686. if (mesh instanceof BABYLON.Mesh) {
  54687. var geometry = mesh.geometry;
  54688. geometryId = geometry ? geometry.id : null;
  54689. }
  54690. else if (mesh instanceof BABYLON.InstancedMesh) {
  54691. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54692. geometryId = geometry ? geometry.id : null;
  54693. }
  54694. var boundingInfo = mesh.getBoundingInfo();
  54695. return {
  54696. uniqueId: mesh.uniqueId,
  54697. id: mesh.id,
  54698. name: mesh.name,
  54699. geometryId: geometryId,
  54700. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54701. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54702. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54703. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54704. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54705. subMeshes: submeshes,
  54706. checkCollisions: mesh.checkCollisions
  54707. };
  54708. };
  54709. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54710. return {
  54711. id: geometry.id,
  54712. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54713. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54714. indices: new Uint32Array(geometry.getIndices() || []),
  54715. };
  54716. };
  54717. return CollisionCoordinatorWorker;
  54718. }());
  54719. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54720. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54721. function CollisionCoordinatorLegacy() {
  54722. this._scaledPosition = BABYLON.Vector3.Zero();
  54723. this._scaledVelocity = BABYLON.Vector3.Zero();
  54724. this._finalPosition = BABYLON.Vector3.Zero();
  54725. }
  54726. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54727. position.divideToRef(collider._radius, this._scaledPosition);
  54728. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54729. collider.collidedMesh = null;
  54730. collider._retry = 0;
  54731. collider._initialVelocity = this._scaledVelocity;
  54732. collider._initialPosition = this._scaledPosition;
  54733. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54734. this._finalPosition.multiplyInPlace(collider._radius);
  54735. //run the callback
  54736. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54737. };
  54738. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54739. this._scene = scene;
  54740. };
  54741. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54742. //Legacy need no destruction method.
  54743. };
  54744. //No update in legacy mode
  54745. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54746. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54747. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54748. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54749. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54750. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54751. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54752. if (excludedMesh === void 0) { excludedMesh = null; }
  54753. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54754. if (collider._retry >= maximumRetry) {
  54755. finalPosition.copyFrom(position);
  54756. return;
  54757. }
  54758. // Check if this is a mesh else camera or -1
  54759. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54760. collider._initialize(position, velocity, closeDistance);
  54761. // Check all meshes
  54762. for (var index = 0; index < this._scene.meshes.length; index++) {
  54763. var mesh = this._scene.meshes[index];
  54764. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54765. mesh._checkCollision(collider);
  54766. }
  54767. }
  54768. if (!collider.collisionFound) {
  54769. position.addToRef(velocity, finalPosition);
  54770. return;
  54771. }
  54772. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54773. collider._getResponse(position, velocity);
  54774. }
  54775. if (velocity.length() <= closeDistance) {
  54776. finalPosition.copyFrom(position);
  54777. return;
  54778. }
  54779. collider._retry++;
  54780. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54781. };
  54782. return CollisionCoordinatorLegacy;
  54783. }());
  54784. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54785. })(BABYLON || (BABYLON = {}));
  54786. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54787. var BABYLON;
  54788. (function (BABYLON) {
  54789. /**
  54790. * A particle represents one of the element emitted by a particle system.
  54791. * This is mainly define by its coordinates, direction, velocity and age.
  54792. */
  54793. var Particle = /** @class */ (function () {
  54794. /**
  54795. * Creates a new instance Particle
  54796. * @param particleSystem the particle system the particle belongs to
  54797. */
  54798. function Particle(
  54799. /**
  54800. * particleSystem the particle system the particle belongs to.
  54801. */
  54802. particleSystem) {
  54803. this.particleSystem = particleSystem;
  54804. /**
  54805. * The world position of the particle in the scene.
  54806. */
  54807. this.position = BABYLON.Vector3.Zero();
  54808. /**
  54809. * The world direction of the particle in the scene.
  54810. */
  54811. this.direction = BABYLON.Vector3.Zero();
  54812. /**
  54813. * The color of the particle.
  54814. */
  54815. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54816. /**
  54817. * The color change of the particle per step.
  54818. */
  54819. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54820. /**
  54821. * Defines how long will the life of the particle be.
  54822. */
  54823. this.lifeTime = 1.0;
  54824. /**
  54825. * The current age of the particle.
  54826. */
  54827. this.age = 0;
  54828. /**
  54829. * The current size of the particle.
  54830. */
  54831. this.size = 0;
  54832. /**
  54833. * The current scale of the particle.
  54834. */
  54835. this.scale = new BABYLON.Vector2(1, 1);
  54836. /**
  54837. * The current angle of the particle.
  54838. */
  54839. this.angle = 0;
  54840. /**
  54841. * Defines how fast is the angle changing.
  54842. */
  54843. this.angularSpeed = 0;
  54844. /**
  54845. * Defines the cell index used by the particle to be rendered from a sprite.
  54846. */
  54847. this.cellIndex = 0;
  54848. /** @hidden */
  54849. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54850. /** @hidden */
  54851. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54852. /** @hidden */
  54853. this._currentSize1 = 0;
  54854. /** @hidden */
  54855. this._currentSize2 = 0;
  54856. /** @hidden */
  54857. this._currentAngularSpeed1 = 0;
  54858. /** @hidden */
  54859. this._currentAngularSpeed2 = 0;
  54860. if (!this.particleSystem.isAnimationSheetEnabled) {
  54861. return;
  54862. }
  54863. this.updateCellInfoFromSystem();
  54864. }
  54865. Particle.prototype.updateCellInfoFromSystem = function () {
  54866. this.cellIndex = this.particleSystem.startSpriteCellID;
  54867. };
  54868. /**
  54869. * Defines how the sprite cell index is updated for the particle
  54870. */
  54871. Particle.prototype.updateCellIndex = function () {
  54872. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54873. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  54874. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54875. };
  54876. /**
  54877. * Copy the properties of particle to another one.
  54878. * @param other the particle to copy the information to.
  54879. */
  54880. Particle.prototype.copyTo = function (other) {
  54881. other.position.copyFrom(this.position);
  54882. if (this._initialDirection) {
  54883. if (other._initialDirection) {
  54884. other._initialDirection.copyFrom(this._initialDirection);
  54885. }
  54886. else {
  54887. other._initialDirection = this._initialDirection.clone();
  54888. }
  54889. }
  54890. else {
  54891. other._initialDirection = null;
  54892. }
  54893. other.direction.copyFrom(this.direction);
  54894. other.color.copyFrom(this.color);
  54895. other.colorStep.copyFrom(this.colorStep);
  54896. other.lifeTime = this.lifeTime;
  54897. other.age = this.age;
  54898. other.size = this.size;
  54899. other.scale.copyFrom(this.scale);
  54900. other.angle = this.angle;
  54901. other.angularSpeed = this.angularSpeed;
  54902. other.particleSystem = this.particleSystem;
  54903. other.cellIndex = this.cellIndex;
  54904. if (this._currentColorGradient) {
  54905. other._currentColorGradient = this._currentColorGradient;
  54906. other._currentColor1.copyFrom(this._currentColor1);
  54907. other._currentColor2.copyFrom(this._currentColor2);
  54908. }
  54909. if (this._currentSizeGradient) {
  54910. other._currentSizeGradient = this._currentSizeGradient;
  54911. other._currentSize1 = this._currentSize1;
  54912. other._currentSize2 = this._currentSize2;
  54913. }
  54914. if (this._currentAngularSpeedGradient) {
  54915. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  54916. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  54917. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  54918. }
  54919. if (this.particleSystem.isAnimationSheetEnabled) {
  54920. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54921. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54922. }
  54923. };
  54924. return Particle;
  54925. }());
  54926. BABYLON.Particle = Particle;
  54927. })(BABYLON || (BABYLON = {}));
  54928. //# sourceMappingURL=babylon.particle.js.map
  54929. var BABYLON;
  54930. (function (BABYLON) {
  54931. /**
  54932. * This represents a particle system in Babylon.
  54933. * 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.
  54934. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54935. * @example https://doc.babylonjs.com/babylon101/particles
  54936. */
  54937. var ParticleSystem = /** @class */ (function () {
  54938. /**
  54939. * Instantiates a particle system.
  54940. * 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.
  54941. * @param name The name of the particle system
  54942. * @param capacity The max number of particles alive at the same time
  54943. * @param scene The scene the particle system belongs to
  54944. * @param customEffect a custom effect used to change the way particles are rendered by default
  54945. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54946. * @param epsilon Offset used to render the particles
  54947. */
  54948. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54949. if (customEffect === void 0) { customEffect = null; }
  54950. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54951. if (epsilon === void 0) { epsilon = 0.01; }
  54952. var _this = this;
  54953. /**
  54954. * List of animations used by the particle system.
  54955. */
  54956. this.animations = [];
  54957. /**
  54958. * The rendering group used by the Particle system to chose when to render.
  54959. */
  54960. this.renderingGroupId = 0;
  54961. /**
  54962. * The emitter represents the Mesh or position we are attaching the particle system to.
  54963. */
  54964. this.emitter = null;
  54965. /**
  54966. * The maximum number of particles to emit per frame
  54967. */
  54968. this.emitRate = 10;
  54969. /**
  54970. * If you want to launch only a few particles at once, that can be done, as well.
  54971. */
  54972. this.manualEmitCount = -1;
  54973. /**
  54974. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54975. */
  54976. this.updateSpeed = 0.01;
  54977. /**
  54978. * The amount of time the particle system is running (depends of the overall update speed).
  54979. */
  54980. this.targetStopDuration = 0;
  54981. /**
  54982. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54983. */
  54984. this.disposeOnStop = false;
  54985. /**
  54986. * Minimum power of emitting particles.
  54987. */
  54988. this.minEmitPower = 1;
  54989. /**
  54990. * Maximum power of emitting particles.
  54991. */
  54992. this.maxEmitPower = 1;
  54993. /**
  54994. * Minimum life time of emitting particles.
  54995. */
  54996. this.minLifeTime = 1;
  54997. /**
  54998. * Maximum life time of emitting particles.
  54999. */
  55000. this.maxLifeTime = 1;
  55001. /**
  55002. * Minimum Size of emitting particles.
  55003. */
  55004. this.minSize = 1;
  55005. /**
  55006. * Maximum Size of emitting particles.
  55007. */
  55008. this.maxSize = 1;
  55009. /**
  55010. * Minimum scale of emitting particles on X axis.
  55011. */
  55012. this.minScaleX = 1;
  55013. /**
  55014. * Maximum scale of emitting particles on X axis.
  55015. */
  55016. this.maxScaleX = 1;
  55017. /**
  55018. * Minimum scale of emitting particles on Y axis.
  55019. */
  55020. this.minScaleY = 1;
  55021. /**
  55022. * Maximum scale of emitting particles on Y axis.
  55023. */
  55024. this.maxScaleY = 1;
  55025. /**
  55026. * Gets or sets the minimal initial rotation in radians.
  55027. */
  55028. this.minInitialRotation = 0;
  55029. /**
  55030. * Gets or sets the maximal initial rotation in radians.
  55031. */
  55032. this.maxInitialRotation = 0;
  55033. /**
  55034. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55035. */
  55036. this.minAngularSpeed = 0;
  55037. /**
  55038. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55039. */
  55040. this.maxAngularSpeed = 0;
  55041. /**
  55042. * The layer mask we are rendering the particles through.
  55043. */
  55044. this.layerMask = 0x0FFFFFFF;
  55045. /**
  55046. * This can help using your own shader to render the particle system.
  55047. * The according effect will be created
  55048. */
  55049. this.customShader = null;
  55050. /**
  55051. * By default particle system starts as soon as they are created. This prevents the
  55052. * automatic start to happen and let you decide when to start emitting particles.
  55053. */
  55054. this.preventAutoStart = false;
  55055. /**
  55056. * Callback triggered when the particle animation is ending.
  55057. */
  55058. this.onAnimationEnd = null;
  55059. /**
  55060. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55061. */
  55062. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55063. /**
  55064. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55065. * to override the particles.
  55066. */
  55067. this.forceDepthWrite = false;
  55068. /**
  55069. * You can use gravity if you want to give an orientation to your particles.
  55070. */
  55071. this.gravity = BABYLON.Vector3.Zero();
  55072. this._colorGradients = null;
  55073. this._sizeGradients = null;
  55074. this._lifeTimeGradients = null;
  55075. this._angularSpeedGradients = null;
  55076. /**
  55077. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55078. */
  55079. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55080. /**
  55081. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55082. */
  55083. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55084. /**
  55085. * Color the particle will have at the end of its lifetime
  55086. */
  55087. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55088. /**
  55089. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55090. */
  55091. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55092. /**
  55093. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55094. */
  55095. this.spriteCellChangeSpeed = 1;
  55096. /**
  55097. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55098. */
  55099. this.startSpriteCellID = 0;
  55100. /**
  55101. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55102. */
  55103. this.endSpriteCellID = 0;
  55104. /**
  55105. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55106. */
  55107. this.spriteCellWidth = 0;
  55108. /**
  55109. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55110. */
  55111. this.spriteCellHeight = 0;
  55112. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55113. this.preWarmCycles = 0;
  55114. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55115. this.preWarmStepOffset = 1;
  55116. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55117. this.translationPivot = new BABYLON.Vector2(0, 0);
  55118. /**
  55119. * An event triggered when the system is disposed
  55120. */
  55121. this.onDisposeObservable = new BABYLON.Observable();
  55122. /**
  55123. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55124. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55125. */
  55126. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55127. this._particles = new Array();
  55128. this._stockParticles = new Array();
  55129. this._newPartsExcess = 0;
  55130. this._vertexBuffers = {};
  55131. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55132. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55133. this._scaledDirection = BABYLON.Vector3.Zero();
  55134. this._scaledGravity = BABYLON.Vector3.Zero();
  55135. this._currentRenderId = -1;
  55136. this._useInstancing = false;
  55137. this._started = false;
  55138. this._stopped = false;
  55139. this._actualFrame = 0;
  55140. this._isBillboardBased = true;
  55141. // start of sub system methods
  55142. /**
  55143. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55144. * Its lifetime will start back at 0.
  55145. */
  55146. this.recycleParticle = function (particle) {
  55147. var lastParticle = _this._particles.pop();
  55148. if (lastParticle !== particle) {
  55149. lastParticle.copyTo(particle);
  55150. }
  55151. _this._stockParticles.push(lastParticle);
  55152. };
  55153. this._createParticle = function () {
  55154. var particle;
  55155. if (_this._stockParticles.length !== 0) {
  55156. particle = _this._stockParticles.pop();
  55157. particle.age = 0;
  55158. particle._currentColorGradient = null;
  55159. particle.cellIndex = _this.startSpriteCellID;
  55160. }
  55161. else {
  55162. particle = new BABYLON.Particle(_this);
  55163. }
  55164. return particle;
  55165. };
  55166. this._emitFromParticle = function (particle) {
  55167. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55168. return;
  55169. }
  55170. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55171. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55172. subSystem._rootParticleSystem = _this;
  55173. _this.activeSubSystems.push(subSystem);
  55174. subSystem.start();
  55175. };
  55176. this.id = name;
  55177. this.name = name;
  55178. this._capacity = capacity;
  55179. this._epsilon = epsilon;
  55180. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55181. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55182. this._customEffect = customEffect;
  55183. scene.particleSystems.push(this);
  55184. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55185. this._createIndexBuffer();
  55186. this._createVertexBuffers();
  55187. // Default emitter type
  55188. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55189. this.updateFunction = function (particles) {
  55190. for (var index = 0; index < particles.length; index++) {
  55191. var particle = particles[index];
  55192. particle.age += _this._scaledUpdateSpeed;
  55193. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55194. _this._emitFromParticle(particle);
  55195. _this.recycleParticle(particle);
  55196. index--;
  55197. continue;
  55198. }
  55199. else {
  55200. var ratio = particle.age / particle.lifeTime;
  55201. // Color
  55202. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55203. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55204. if (currentGradient !== particle._currentColorGradient) {
  55205. particle._currentColor1.copyFrom(particle._currentColor2);
  55206. nextGradient.getColorToRef(particle._currentColor2);
  55207. particle._currentColorGradient = currentGradient;
  55208. }
  55209. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55210. });
  55211. }
  55212. else {
  55213. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55214. particle.color.addInPlace(_this._scaledColorStep);
  55215. if (particle.color.a < 0) {
  55216. particle.color.a = 0;
  55217. }
  55218. }
  55219. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  55220. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  55221. if (currentGradient !== particle._currentAngularSpeedGradient) {
  55222. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  55223. particle._currentAngularSpeed2 = nextGradient.getFactor();
  55224. particle._currentAngularSpeedGradient = currentGradient;
  55225. }
  55226. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  55227. });
  55228. }
  55229. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55230. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55231. particle.position.addInPlace(_this._scaledDirection);
  55232. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55233. particle.direction.addInPlace(_this._scaledGravity);
  55234. // Size
  55235. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55236. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55237. if (currentGradient !== particle._currentSizeGradient) {
  55238. particle._currentSize1 = particle._currentSize2;
  55239. particle._currentSize2 = nextGradient.getFactor();
  55240. particle._currentSizeGradient = currentGradient;
  55241. }
  55242. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55243. });
  55244. }
  55245. if (_this._isAnimationSheetEnabled) {
  55246. particle.updateCellIndex();
  55247. }
  55248. }
  55249. }
  55250. };
  55251. }
  55252. /**
  55253. * Gets the current list of color gradients.
  55254. * You must use addColorGradient and removeColorGradient to udpate this list
  55255. * @returns the list of color gradients
  55256. */
  55257. ParticleSystem.prototype.getColorGradients = function () {
  55258. return this._colorGradients;
  55259. };
  55260. /**
  55261. * Gets the current list of size gradients.
  55262. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55263. * @returns the list of size gradients
  55264. */
  55265. ParticleSystem.prototype.getSizeGradients = function () {
  55266. return this._sizeGradients;
  55267. };
  55268. /**
  55269. * Gets the current list of life time gradients.
  55270. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55271. * @returns the list of life time gradients
  55272. */
  55273. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55274. return this._lifeTimeGradients;
  55275. };
  55276. /**
  55277. * Gets the current list of angular speed gradients.
  55278. * You must use addAngularSpeedGradient and removeAngularGradient to udpate this list
  55279. * @returns the list of angular speed gradients
  55280. */
  55281. ParticleSystem.prototype.getAngularSpeedGradients = function () {
  55282. return this._angularSpeedGradients;
  55283. };
  55284. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55285. /**
  55286. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55287. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55288. */
  55289. get: function () {
  55290. if (this.particleEmitterType.direction1) {
  55291. return this.particleEmitterType.direction1;
  55292. }
  55293. return BABYLON.Vector3.Zero();
  55294. },
  55295. set: function (value) {
  55296. if (this.particleEmitterType.direction1) {
  55297. this.particleEmitterType.direction1 = value;
  55298. }
  55299. },
  55300. enumerable: true,
  55301. configurable: true
  55302. });
  55303. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55304. /**
  55305. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55306. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55307. */
  55308. get: function () {
  55309. if (this.particleEmitterType.direction2) {
  55310. return this.particleEmitterType.direction2;
  55311. }
  55312. return BABYLON.Vector3.Zero();
  55313. },
  55314. set: function (value) {
  55315. if (this.particleEmitterType.direction2) {
  55316. this.particleEmitterType.direction2 = value;
  55317. }
  55318. },
  55319. enumerable: true,
  55320. configurable: true
  55321. });
  55322. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55323. /**
  55324. * 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.
  55325. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55326. */
  55327. get: function () {
  55328. if (this.particleEmitterType.minEmitBox) {
  55329. return this.particleEmitterType.minEmitBox;
  55330. }
  55331. return BABYLON.Vector3.Zero();
  55332. },
  55333. set: function (value) {
  55334. if (this.particleEmitterType.minEmitBox) {
  55335. this.particleEmitterType.minEmitBox = value;
  55336. }
  55337. },
  55338. enumerable: true,
  55339. configurable: true
  55340. });
  55341. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55342. /**
  55343. * 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.
  55344. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55345. */
  55346. get: function () {
  55347. if (this.particleEmitterType.maxEmitBox) {
  55348. return this.particleEmitterType.maxEmitBox;
  55349. }
  55350. return BABYLON.Vector3.Zero();
  55351. },
  55352. set: function (value) {
  55353. if (this.particleEmitterType.maxEmitBox) {
  55354. this.particleEmitterType.maxEmitBox = value;
  55355. }
  55356. },
  55357. enumerable: true,
  55358. configurable: true
  55359. });
  55360. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55361. /**
  55362. * Sets a callback that will be triggered when the system is disposed
  55363. */
  55364. set: function (callback) {
  55365. if (this._onDisposeObserver) {
  55366. this.onDisposeObservable.remove(this._onDisposeObserver);
  55367. }
  55368. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55369. },
  55370. enumerable: true,
  55371. configurable: true
  55372. });
  55373. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55374. /**
  55375. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55376. */
  55377. get: function () {
  55378. return this._isAnimationSheetEnabled;
  55379. },
  55380. enumerable: true,
  55381. configurable: true
  55382. });
  55383. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55384. /**
  55385. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55386. */
  55387. get: function () {
  55388. return this._isBillboardBased;
  55389. },
  55390. set: function (value) {
  55391. if (this._isBillboardBased === value) {
  55392. return;
  55393. }
  55394. this._isBillboardBased = value;
  55395. this._resetEffect();
  55396. },
  55397. enumerable: true,
  55398. configurable: true
  55399. });
  55400. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55401. //end of Sub-emitter
  55402. /**
  55403. * Gets the current list of active particles
  55404. */
  55405. get: function () {
  55406. return this._particles;
  55407. },
  55408. enumerable: true,
  55409. configurable: true
  55410. });
  55411. /**
  55412. * Returns the string "ParticleSystem"
  55413. * @returns a string containing the class name
  55414. */
  55415. ParticleSystem.prototype.getClassName = function () {
  55416. return "ParticleSystem";
  55417. };
  55418. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55419. var newGradient = new BABYLON.FactorGradient();
  55420. newGradient.gradient = gradient;
  55421. newGradient.factor1 = factor;
  55422. newGradient.factor2 = factor2;
  55423. factorGradients.push(newGradient);
  55424. factorGradients.sort(function (a, b) {
  55425. if (a.gradient < b.gradient) {
  55426. return -1;
  55427. }
  55428. else if (a.gradient > b.gradient) {
  55429. return 1;
  55430. }
  55431. return 0;
  55432. });
  55433. };
  55434. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55435. if (!factorGradients) {
  55436. return;
  55437. }
  55438. var index = 0;
  55439. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55440. var factorGradient = factorGradients_1[_i];
  55441. if (factorGradient.gradient === gradient) {
  55442. factorGradients.splice(index, 1);
  55443. break;
  55444. }
  55445. index++;
  55446. }
  55447. };
  55448. /**
  55449. * Adds a new life time gradient
  55450. * @param gradient defines the gradient to use (between 0 and 1)
  55451. * @param factor defines the life time factor to affect to the specified gradient
  55452. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55453. * @returns the current particle system
  55454. */
  55455. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55456. if (!this._lifeTimeGradients) {
  55457. this._lifeTimeGradients = [];
  55458. }
  55459. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55460. return this;
  55461. };
  55462. /**
  55463. * Remove a specific life time gradient
  55464. * @param gradient defines the gradient to remove
  55465. * @returns the current particle system
  55466. */
  55467. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55468. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55469. return this;
  55470. };
  55471. /**
  55472. * Adds a new size gradient
  55473. * @param gradient defines the gradient to use (between 0 and 1)
  55474. * @param factor defines the size factor to affect to the specified gradient
  55475. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55476. * @returns the current particle system
  55477. */
  55478. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55479. if (!this._sizeGradients) {
  55480. this._sizeGradients = [];
  55481. }
  55482. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55483. return this;
  55484. };
  55485. /**
  55486. * Remove a specific size gradient
  55487. * @param gradient defines the gradient to remove
  55488. * @returns the current particle system
  55489. */
  55490. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55491. this._removeFactorGradient(this._sizeGradients, gradient);
  55492. return this;
  55493. };
  55494. /**
  55495. * Adds a new angular speed gradient
  55496. * @param gradient defines the gradient to use (between 0 and 1)
  55497. * @param factor defines the size factor to affect to the specified gradient
  55498. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55499. * @returns the current particle system
  55500. */
  55501. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  55502. if (!this._angularSpeedGradients) {
  55503. this._angularSpeedGradients = [];
  55504. }
  55505. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  55506. return this;
  55507. };
  55508. /**
  55509. * Remove a specific angular speed gradient
  55510. * @param gradient defines the gradient to remove
  55511. * @returns the current particle system
  55512. */
  55513. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  55514. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  55515. return this;
  55516. };
  55517. /**
  55518. * Adds a new color gradient
  55519. * @param gradient defines the gradient to use (between 0 and 1)
  55520. * @param color defines the color to affect to the specified gradient
  55521. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55522. */
  55523. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55524. if (!this._colorGradients) {
  55525. this._colorGradients = [];
  55526. }
  55527. var colorGradient = new BABYLON.ColorGradient();
  55528. colorGradient.gradient = gradient;
  55529. colorGradient.color1 = color;
  55530. colorGradient.color2 = color2;
  55531. this._colorGradients.push(colorGradient);
  55532. this._colorGradients.sort(function (a, b) {
  55533. if (a.gradient < b.gradient) {
  55534. return -1;
  55535. }
  55536. else if (a.gradient > b.gradient) {
  55537. return 1;
  55538. }
  55539. return 0;
  55540. });
  55541. return this;
  55542. };
  55543. /**
  55544. * Remove a specific color gradient
  55545. * @param gradient defines the gradient to remove
  55546. */
  55547. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55548. if (!this._colorGradients) {
  55549. return this;
  55550. }
  55551. var index = 0;
  55552. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55553. var colorGradient = _a[_i];
  55554. if (colorGradient.gradient === gradient) {
  55555. this._colorGradients.splice(index, 1);
  55556. break;
  55557. }
  55558. index++;
  55559. }
  55560. return this;
  55561. };
  55562. ParticleSystem.prototype._resetEffect = function () {
  55563. if (this._vertexBuffer) {
  55564. this._vertexBuffer.dispose();
  55565. this._vertexBuffer = null;
  55566. }
  55567. if (this._spriteBuffer) {
  55568. this._spriteBuffer.dispose();
  55569. this._spriteBuffer = null;
  55570. }
  55571. this._createVertexBuffers();
  55572. };
  55573. ParticleSystem.prototype._createVertexBuffers = function () {
  55574. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55575. if (this._isAnimationSheetEnabled) {
  55576. this._vertexBufferSize += 1;
  55577. }
  55578. if (!this._isBillboardBased) {
  55579. this._vertexBufferSize += 3;
  55580. }
  55581. var engine = this._scene.getEngine();
  55582. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55583. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55584. var dataOffset = 0;
  55585. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55586. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55587. dataOffset += 3;
  55588. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55589. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55590. dataOffset += 4;
  55591. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55592. this._vertexBuffers["angle"] = options;
  55593. dataOffset += 1;
  55594. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55595. this._vertexBuffers["size"] = size;
  55596. dataOffset += 2;
  55597. if (this._isAnimationSheetEnabled) {
  55598. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55599. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55600. dataOffset += 1;
  55601. }
  55602. if (!this._isBillboardBased) {
  55603. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55604. this._vertexBuffers["direction"] = directionBuffer;
  55605. dataOffset += 3;
  55606. }
  55607. var offsets;
  55608. if (this._useInstancing) {
  55609. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55610. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55611. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55612. }
  55613. else {
  55614. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55615. dataOffset += 2;
  55616. }
  55617. this._vertexBuffers["offset"] = offsets;
  55618. };
  55619. ParticleSystem.prototype._createIndexBuffer = function () {
  55620. if (this._useInstancing) {
  55621. return;
  55622. }
  55623. var indices = [];
  55624. var index = 0;
  55625. for (var count = 0; count < this._capacity; count++) {
  55626. indices.push(index);
  55627. indices.push(index + 1);
  55628. indices.push(index + 2);
  55629. indices.push(index);
  55630. indices.push(index + 2);
  55631. indices.push(index + 3);
  55632. index += 4;
  55633. }
  55634. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55635. };
  55636. /**
  55637. * Gets the maximum number of particles active at the same time.
  55638. * @returns The max number of active particles.
  55639. */
  55640. ParticleSystem.prototype.getCapacity = function () {
  55641. return this._capacity;
  55642. };
  55643. /**
  55644. * Gets Wether there are still active particles in the system.
  55645. * @returns True if it is alive, otherwise false.
  55646. */
  55647. ParticleSystem.prototype.isAlive = function () {
  55648. return this._alive;
  55649. };
  55650. /**
  55651. * Gets Wether the system has been started.
  55652. * @returns True if it has been started, otherwise false.
  55653. */
  55654. ParticleSystem.prototype.isStarted = function () {
  55655. return this._started;
  55656. };
  55657. /**
  55658. * Starts the particle system and begins to emit.
  55659. */
  55660. ParticleSystem.prototype.start = function () {
  55661. this._started = true;
  55662. this._stopped = false;
  55663. this._actualFrame = 0;
  55664. if (this.subEmitters && this.subEmitters.length != 0) {
  55665. this.activeSubSystems = new Array();
  55666. }
  55667. if (this.preWarmCycles) {
  55668. for (var index = 0; index < this.preWarmCycles; index++) {
  55669. this.animate(true);
  55670. }
  55671. }
  55672. };
  55673. /**
  55674. * Stops the particle system.
  55675. * @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.
  55676. */
  55677. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55678. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55679. this._stopped = true;
  55680. if (stopSubEmitters) {
  55681. this._stopSubEmitters();
  55682. }
  55683. };
  55684. // animation sheet
  55685. /**
  55686. * Remove all active particles
  55687. */
  55688. ParticleSystem.prototype.reset = function () {
  55689. this._stockParticles = [];
  55690. this._particles = [];
  55691. };
  55692. /**
  55693. * @hidden (for internal use only)
  55694. */
  55695. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55696. var offset = index * this._vertexBufferSize;
  55697. this._vertexData[offset++] = particle.position.x;
  55698. this._vertexData[offset++] = particle.position.y;
  55699. this._vertexData[offset++] = particle.position.z;
  55700. this._vertexData[offset++] = particle.color.r;
  55701. this._vertexData[offset++] = particle.color.g;
  55702. this._vertexData[offset++] = particle.color.b;
  55703. this._vertexData[offset++] = particle.color.a;
  55704. this._vertexData[offset++] = particle.angle;
  55705. this._vertexData[offset++] = particle.scale.x * particle.size;
  55706. this._vertexData[offset++] = particle.scale.y * particle.size;
  55707. if (this._isAnimationSheetEnabled) {
  55708. this._vertexData[offset++] = particle.cellIndex;
  55709. }
  55710. if (!this._isBillboardBased) {
  55711. if (particle._initialDirection) {
  55712. this._vertexData[offset++] = particle._initialDirection.x;
  55713. this._vertexData[offset++] = particle._initialDirection.y;
  55714. this._vertexData[offset++] = particle._initialDirection.z;
  55715. }
  55716. else {
  55717. this._vertexData[offset++] = particle.direction.x;
  55718. this._vertexData[offset++] = particle.direction.y;
  55719. this._vertexData[offset++] = particle.direction.z;
  55720. }
  55721. }
  55722. if (!this._useInstancing) {
  55723. if (this._isAnimationSheetEnabled) {
  55724. if (offsetX === 0)
  55725. offsetX = this._epsilon;
  55726. else if (offsetX === 1)
  55727. offsetX = 1 - this._epsilon;
  55728. if (offsetY === 0)
  55729. offsetY = this._epsilon;
  55730. else if (offsetY === 1)
  55731. offsetY = 1 - this._epsilon;
  55732. }
  55733. this._vertexData[offset++] = offsetX;
  55734. this._vertexData[offset++] = offsetY;
  55735. }
  55736. };
  55737. ParticleSystem.prototype._stopSubEmitters = function () {
  55738. if (!this.activeSubSystems) {
  55739. return;
  55740. }
  55741. this.activeSubSystems.forEach(function (subSystem) {
  55742. subSystem.stop(true);
  55743. });
  55744. this.activeSubSystems = new Array();
  55745. };
  55746. ParticleSystem.prototype._removeFromRoot = function () {
  55747. if (!this._rootParticleSystem) {
  55748. return;
  55749. }
  55750. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55751. if (index !== -1) {
  55752. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55753. }
  55754. };
  55755. // End of sub system methods
  55756. ParticleSystem.prototype._update = function (newParticles) {
  55757. // Update current
  55758. this._alive = this._particles.length > 0;
  55759. this.updateFunction(this._particles);
  55760. // Add new ones
  55761. var worldMatrix;
  55762. if (this.emitter.position) {
  55763. var emitterMesh = this.emitter;
  55764. worldMatrix = emitterMesh.getWorldMatrix();
  55765. }
  55766. else {
  55767. var emitterPosition = this.emitter;
  55768. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55769. }
  55770. var particle;
  55771. var _loop_1 = function () {
  55772. if (this_1._particles.length === this_1._capacity) {
  55773. return "break";
  55774. }
  55775. particle = this_1._createParticle();
  55776. this_1._particles.push(particle);
  55777. // Emitter
  55778. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55779. if (this_1.startPositionFunction) {
  55780. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55781. }
  55782. else {
  55783. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55784. }
  55785. if (this_1.startDirectionFunction) {
  55786. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55787. }
  55788. else {
  55789. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55790. }
  55791. if (emitPower === 0) {
  55792. if (!particle._initialDirection) {
  55793. particle._initialDirection = particle.direction.clone();
  55794. }
  55795. else {
  55796. particle._initialDirection.copyFrom(particle.direction);
  55797. }
  55798. }
  55799. else {
  55800. particle._initialDirection = null;
  55801. }
  55802. particle.direction.scaleInPlace(emitPower);
  55803. // Life time
  55804. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55805. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55806. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55807. var factorGradient1 = currentGradient;
  55808. var factorGradient2 = nextGradient;
  55809. var lifeTime1 = factorGradient1.getFactor();
  55810. var lifeTime2 = factorGradient2.getFactor();
  55811. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55812. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55813. });
  55814. }
  55815. else {
  55816. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55817. }
  55818. // Size
  55819. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55820. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55821. }
  55822. else {
  55823. particle._currentSizeGradient = this_1._sizeGradients[0];
  55824. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55825. particle.size = particle._currentSize1;
  55826. if (this_1._sizeGradients.length > 1) {
  55827. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55828. }
  55829. else {
  55830. particle._currentSize2 = particle._currentSize1;
  55831. }
  55832. }
  55833. // Size and scale
  55834. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55835. // Angle
  55836. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  55837. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55838. }
  55839. else {
  55840. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  55841. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  55842. particle._currentAngularSpeed1 = particle.angularSpeed;
  55843. if (this_1._angularSpeedGradients.length > 1) {
  55844. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  55845. }
  55846. else {
  55847. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  55848. }
  55849. }
  55850. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55851. // Color
  55852. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55853. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55854. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55855. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55856. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55857. }
  55858. else {
  55859. particle._currentColorGradient = this_1._colorGradients[0];
  55860. particle._currentColorGradient.getColorToRef(particle.color);
  55861. particle._currentColor1.copyFrom(particle.color);
  55862. if (this_1._colorGradients.length > 1) {
  55863. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55864. }
  55865. else {
  55866. particle._currentColor2.copyFrom(particle.color);
  55867. }
  55868. }
  55869. // Sheet
  55870. if (this_1._isAnimationSheetEnabled) {
  55871. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55872. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55873. }
  55874. };
  55875. var this_1 = this, step;
  55876. for (var index = 0; index < newParticles; index++) {
  55877. var state_1 = _loop_1();
  55878. if (state_1 === "break")
  55879. break;
  55880. }
  55881. };
  55882. /** @hidden */
  55883. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55884. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55885. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55886. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55887. if (isAnimationSheetEnabled) {
  55888. attributeNamesOrOptions.push("cellIndex");
  55889. }
  55890. if (!isBillboardBased) {
  55891. attributeNamesOrOptions.push("direction");
  55892. }
  55893. return attributeNamesOrOptions;
  55894. };
  55895. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55896. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55897. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55898. if (isAnimationSheetEnabled) {
  55899. effectCreationOption.push("particlesInfos");
  55900. }
  55901. return effectCreationOption;
  55902. };
  55903. ParticleSystem.prototype._getEffect = function () {
  55904. if (this._customEffect) {
  55905. return this._customEffect;
  55906. }
  55907. ;
  55908. var defines = [];
  55909. if (this._scene.clipPlane) {
  55910. defines.push("#define CLIPPLANE");
  55911. }
  55912. if (this._isAnimationSheetEnabled) {
  55913. defines.push("#define ANIMATESHEET");
  55914. }
  55915. if (this._isBillboardBased) {
  55916. defines.push("#define BILLBOARD");
  55917. switch (this.billboardMode) {
  55918. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  55919. defines.push("#define BILLBOARDY");
  55920. break;
  55921. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  55922. default:
  55923. break;
  55924. }
  55925. }
  55926. // Effect
  55927. var join = defines.join("\n");
  55928. if (this._cachedDefines !== join) {
  55929. this._cachedDefines = join;
  55930. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55931. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55932. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55933. }
  55934. return this._effect;
  55935. };
  55936. /**
  55937. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55938. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55939. */
  55940. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55941. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55942. if (!this._started)
  55943. return;
  55944. if (!preWarmOnly) {
  55945. var effect = this._getEffect();
  55946. // Check
  55947. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55948. return;
  55949. if (this._currentRenderId === this._scene.getRenderId()) {
  55950. return;
  55951. }
  55952. this._currentRenderId = this._scene.getRenderId();
  55953. }
  55954. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55955. // determine the number of particles we need to create
  55956. var newParticles;
  55957. if (this.manualEmitCount > -1) {
  55958. newParticles = this.manualEmitCount;
  55959. this._newPartsExcess = 0;
  55960. this.manualEmitCount = 0;
  55961. }
  55962. else {
  55963. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55964. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55965. }
  55966. if (this._newPartsExcess > 1.0) {
  55967. newParticles += this._newPartsExcess >> 0;
  55968. this._newPartsExcess -= this._newPartsExcess >> 0;
  55969. }
  55970. this._alive = false;
  55971. if (!this._stopped) {
  55972. this._actualFrame += this._scaledUpdateSpeed;
  55973. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55974. this.stop();
  55975. }
  55976. else {
  55977. newParticles = 0;
  55978. }
  55979. this._update(newParticles);
  55980. // Stopped?
  55981. if (this._stopped) {
  55982. if (!this._alive) {
  55983. this._started = false;
  55984. if (this.onAnimationEnd) {
  55985. this.onAnimationEnd();
  55986. }
  55987. if (this.disposeOnStop) {
  55988. this._scene._toBeDisposed.push(this);
  55989. }
  55990. }
  55991. }
  55992. if (!preWarmOnly) {
  55993. // Update VBO
  55994. var offset = 0;
  55995. for (var index = 0; index < this._particles.length; index++) {
  55996. var particle = this._particles[index];
  55997. this._appendParticleVertices(offset, particle);
  55998. offset += this._useInstancing ? 1 : 4;
  55999. }
  56000. if (this._vertexBuffer) {
  56001. this._vertexBuffer.update(this._vertexData);
  56002. }
  56003. }
  56004. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56005. this.stop();
  56006. }
  56007. };
  56008. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56009. this._appendParticleVertex(offset++, particle, 0, 0);
  56010. if (!this._useInstancing) {
  56011. this._appendParticleVertex(offset++, particle, 1, 0);
  56012. this._appendParticleVertex(offset++, particle, 1, 1);
  56013. this._appendParticleVertex(offset++, particle, 0, 1);
  56014. }
  56015. };
  56016. /**
  56017. * Rebuilds the particle system.
  56018. */
  56019. ParticleSystem.prototype.rebuild = function () {
  56020. this._createIndexBuffer();
  56021. if (this._vertexBuffer) {
  56022. this._vertexBuffer._rebuild();
  56023. }
  56024. };
  56025. /**
  56026. * Is this system ready to be used/rendered
  56027. * @return true if the system is ready
  56028. */
  56029. ParticleSystem.prototype.isReady = function () {
  56030. var effect = this._getEffect();
  56031. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56032. return false;
  56033. }
  56034. return true;
  56035. };
  56036. /**
  56037. * Renders the particle system in its current state.
  56038. * @returns the current number of particles
  56039. */
  56040. ParticleSystem.prototype.render = function () {
  56041. var effect = this._getEffect();
  56042. // Check
  56043. if (!this.isReady() || !this._particles.length) {
  56044. return 0;
  56045. }
  56046. var engine = this._scene.getEngine();
  56047. // Render
  56048. engine.enableEffect(effect);
  56049. engine.setState(false);
  56050. var viewMatrix = this._scene.getViewMatrix();
  56051. effect.setTexture("diffuseSampler", this.particleTexture);
  56052. effect.setMatrix("view", viewMatrix);
  56053. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56054. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56055. var baseSize = this.particleTexture.getBaseSize();
  56056. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56057. }
  56058. effect.setVector2("translationPivot", this.translationPivot);
  56059. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56060. if (this._isBillboardBased) {
  56061. var camera = this._scene.activeCamera;
  56062. effect.setVector3("eyePosition", camera.globalPosition);
  56063. }
  56064. if (this._scene.clipPlane) {
  56065. var clipPlane = this._scene.clipPlane;
  56066. var invView = viewMatrix.clone();
  56067. invView.invert();
  56068. effect.setMatrix("invView", invView);
  56069. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56070. }
  56071. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56072. // Draw order
  56073. switch (this.blendMode) {
  56074. case ParticleSystem.BLENDMODE_ADD:
  56075. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56076. break;
  56077. case ParticleSystem.BLENDMODE_ONEONE:
  56078. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56079. break;
  56080. case ParticleSystem.BLENDMODE_STANDARD:
  56081. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56082. break;
  56083. }
  56084. if (this.forceDepthWrite) {
  56085. engine.setDepthWrite(true);
  56086. }
  56087. if (this._useInstancing) {
  56088. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56089. engine.unbindInstanceAttributes();
  56090. }
  56091. else {
  56092. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56093. }
  56094. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56095. return this._particles.length;
  56096. };
  56097. /**
  56098. * Disposes the particle system and free the associated resources
  56099. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56100. */
  56101. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56102. if (disposeTexture === void 0) { disposeTexture = true; }
  56103. if (this._vertexBuffer) {
  56104. this._vertexBuffer.dispose();
  56105. this._vertexBuffer = null;
  56106. }
  56107. if (this._spriteBuffer) {
  56108. this._spriteBuffer.dispose();
  56109. this._spriteBuffer = null;
  56110. }
  56111. if (this._indexBuffer) {
  56112. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56113. this._indexBuffer = null;
  56114. }
  56115. if (disposeTexture && this.particleTexture) {
  56116. this.particleTexture.dispose();
  56117. this.particleTexture = null;
  56118. }
  56119. this._removeFromRoot();
  56120. // Remove from scene
  56121. var index = this._scene.particleSystems.indexOf(this);
  56122. if (index > -1) {
  56123. this._scene.particleSystems.splice(index, 1);
  56124. }
  56125. // Callback
  56126. this.onDisposeObservable.notifyObservers(this);
  56127. this.onDisposeObservable.clear();
  56128. };
  56129. /**
  56130. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56131. * @param radius The radius of the sphere to emit from
  56132. * @returns the emitter
  56133. */
  56134. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56135. if (radius === void 0) { radius = 1; }
  56136. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56137. this.particleEmitterType = particleEmitter;
  56138. return particleEmitter;
  56139. };
  56140. /**
  56141. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56142. * @param radius The radius of the sphere to emit from
  56143. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56144. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56145. * @returns the emitter
  56146. */
  56147. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56148. if (radius === void 0) { radius = 1; }
  56149. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56150. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56151. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56152. this.particleEmitterType = particleEmitter;
  56153. return particleEmitter;
  56154. };
  56155. /**
  56156. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56157. * @param radius The radius of the cone to emit from
  56158. * @param angle The base angle of the cone
  56159. * @returns the emitter
  56160. */
  56161. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56162. if (radius === void 0) { radius = 1; }
  56163. if (angle === void 0) { angle = Math.PI / 4; }
  56164. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56165. this.particleEmitterType = particleEmitter;
  56166. return particleEmitter;
  56167. };
  56168. // 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.
  56169. /**
  56170. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56171. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56172. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56173. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56174. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56175. * @returns the emitter
  56176. */
  56177. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56178. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56179. this.particleEmitterType = particleEmitter;
  56180. this.direction1 = direction1;
  56181. this.direction2 = direction2;
  56182. this.minEmitBox = minEmitBox;
  56183. this.maxEmitBox = maxEmitBox;
  56184. return particleEmitter;
  56185. };
  56186. // Clone
  56187. /**
  56188. * Clones the particle system.
  56189. * @param name The name of the cloned object
  56190. * @param newEmitter The new emitter to use
  56191. * @returns the cloned particle system
  56192. */
  56193. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56194. var custom = null;
  56195. var program = null;
  56196. if (this.customShader != null) {
  56197. program = this.customShader;
  56198. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56199. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56200. }
  56201. else if (this._customEffect) {
  56202. custom = this._customEffect;
  56203. }
  56204. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56205. result.customShader = program;
  56206. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56207. if (newEmitter === undefined) {
  56208. newEmitter = this.emitter;
  56209. }
  56210. result.emitter = newEmitter;
  56211. if (this.particleTexture) {
  56212. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56213. }
  56214. if (!this.preventAutoStart) {
  56215. result.start();
  56216. }
  56217. return result;
  56218. };
  56219. /**
  56220. * Serializes the particle system to a JSON object.
  56221. * @returns the JSON object
  56222. */
  56223. ParticleSystem.prototype.serialize = function () {
  56224. var serializationObject = {};
  56225. ParticleSystem._Serialize(serializationObject, this);
  56226. serializationObject.textureMask = this.textureMask.asArray();
  56227. serializationObject.customShader = this.customShader;
  56228. serializationObject.preventAutoStart = this.preventAutoStart;
  56229. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56230. return serializationObject;
  56231. };
  56232. /** @hidden */
  56233. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56234. serializationObject.name = particleSystem.name;
  56235. serializationObject.id = particleSystem.id;
  56236. serializationObject.capacity = particleSystem.getCapacity();
  56237. // Emitter
  56238. if (particleSystem.emitter.position) {
  56239. var emitterMesh = particleSystem.emitter;
  56240. serializationObject.emitterId = emitterMesh.id;
  56241. }
  56242. else {
  56243. var emitterPosition = particleSystem.emitter;
  56244. serializationObject.emitter = emitterPosition.asArray();
  56245. }
  56246. // Emitter
  56247. if (particleSystem.particleEmitterType) {
  56248. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56249. }
  56250. if (particleSystem.particleTexture) {
  56251. serializationObject.textureName = particleSystem.particleTexture.name;
  56252. }
  56253. // Animations
  56254. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56255. // Particle system
  56256. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56257. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56258. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56259. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56260. serializationObject.minSize = particleSystem.minSize;
  56261. serializationObject.maxSize = particleSystem.maxSize;
  56262. serializationObject.minScaleX = particleSystem.minScaleX;
  56263. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56264. serializationObject.minScaleY = particleSystem.minScaleY;
  56265. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56266. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56267. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56268. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56269. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56270. serializationObject.emitRate = particleSystem.emitRate;
  56271. serializationObject.gravity = particleSystem.gravity.asArray();
  56272. serializationObject.color1 = particleSystem.color1.asArray();
  56273. serializationObject.color2 = particleSystem.color2.asArray();
  56274. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56275. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56276. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56277. serializationObject.blendMode = particleSystem.blendMode;
  56278. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56279. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56280. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56281. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56282. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56283. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56284. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56285. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56286. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56287. var colorGradients = particleSystem.getColorGradients();
  56288. if (colorGradients) {
  56289. serializationObject.colorGradients = [];
  56290. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56291. var colorGradient = colorGradients_1[_i];
  56292. var serializedGradient = {
  56293. gradient: colorGradient.gradient,
  56294. color1: colorGradient.color1.asArray()
  56295. };
  56296. if (colorGradient.color2) {
  56297. serializedGradient.color2 = colorGradient.color2.asArray();
  56298. }
  56299. serializationObject.colorGradients.push(serializedGradient);
  56300. }
  56301. }
  56302. var sizeGradients = particleSystem.getSizeGradients();
  56303. if (sizeGradients) {
  56304. serializationObject.sizeGradients = [];
  56305. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56306. var sizeGradient = sizeGradients_1[_a];
  56307. var serializedGradient = {
  56308. gradient: sizeGradient.gradient,
  56309. factor1: sizeGradient.factor1
  56310. };
  56311. if (sizeGradient.factor2 !== undefined) {
  56312. serializedGradient.factor2 = sizeGradient.factor2;
  56313. }
  56314. serializationObject.sizeGradients.push(serializedGradient);
  56315. }
  56316. }
  56317. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  56318. if (angularSpeedGradients) {
  56319. serializationObject.angularSpeedGradients = [];
  56320. for (var _b = 0, angularSpeedGradients_1 = angularSpeedGradients; _b < angularSpeedGradients_1.length; _b++) {
  56321. var angularSpeedGradient = angularSpeedGradients_1[_b];
  56322. var serializedGradient = {
  56323. gradient: angularSpeedGradient.gradient,
  56324. factor1: angularSpeedGradient.factor1
  56325. };
  56326. if (angularSpeedGradient.factor2 !== undefined) {
  56327. serializedGradient.factor2 = angularSpeedGradient.factor2;
  56328. }
  56329. serializationObject.angularSpeedGradients.push(serializedGradient);
  56330. }
  56331. }
  56332. };
  56333. /** @hidden */
  56334. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56335. // Texture
  56336. if (parsedParticleSystem.textureName) {
  56337. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56338. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56339. }
  56340. // Emitter
  56341. if (parsedParticleSystem.emitterId === undefined) {
  56342. particleSystem.emitter = BABYLON.Vector3.Zero();
  56343. }
  56344. else if (parsedParticleSystem.emitterId) {
  56345. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56346. }
  56347. else {
  56348. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56349. }
  56350. // Misc.
  56351. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56352. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56353. }
  56354. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56355. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56356. }
  56357. // Animations
  56358. if (parsedParticleSystem.animations) {
  56359. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56360. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56361. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56362. }
  56363. }
  56364. if (parsedParticleSystem.autoAnimate) {
  56365. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56366. }
  56367. // Particle system
  56368. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56369. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56370. particleSystem.minSize = parsedParticleSystem.minSize;
  56371. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56372. if (parsedParticleSystem.minScaleX) {
  56373. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56374. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56375. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56376. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56377. }
  56378. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56379. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56380. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56381. }
  56382. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56383. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56384. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56385. }
  56386. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56387. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56388. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56389. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56390. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56391. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56392. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56393. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56394. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56395. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56396. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56397. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56398. if (parsedParticleSystem.colorGradients) {
  56399. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56400. var colorGradient = _a[_i];
  56401. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56402. }
  56403. }
  56404. if (parsedParticleSystem.sizeGradients) {
  56405. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56406. var sizeGradient = _c[_b];
  56407. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56408. }
  56409. }
  56410. if (parsedParticleSystem.angularSpeedGradients) {
  56411. for (var _d = 0, _e = parsedParticleSystem.angularSpeedGradients; _d < _e.length; _d++) {
  56412. var angularSpeedGradient = _e[_d];
  56413. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  56414. }
  56415. }
  56416. // Emitter
  56417. var emitterType;
  56418. if (parsedParticleSystem.particleEmitterType) {
  56419. switch (parsedParticleSystem.particleEmitterType.type) {
  56420. case "SphereParticleEmitter":
  56421. emitterType = new BABYLON.SphereParticleEmitter();
  56422. break;
  56423. case "SphereDirectedParticleEmitter":
  56424. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56425. break;
  56426. case "ConeEmitter":
  56427. case "ConeParticleEmitter":
  56428. emitterType = new BABYLON.ConeParticleEmitter();
  56429. break;
  56430. case "BoxEmitter":
  56431. case "BoxParticleEmitter":
  56432. default:
  56433. emitterType = new BABYLON.BoxParticleEmitter();
  56434. break;
  56435. }
  56436. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56437. }
  56438. else {
  56439. emitterType = new BABYLON.BoxParticleEmitter();
  56440. emitterType.parse(parsedParticleSystem);
  56441. }
  56442. particleSystem.particleEmitterType = emitterType;
  56443. // Animation sheet
  56444. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56445. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56446. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56447. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56448. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56449. };
  56450. /**
  56451. * Parses a JSON object to create a particle system.
  56452. * @param parsedParticleSystem The JSON object to parse
  56453. * @param scene The scene to create the particle system in
  56454. * @param rootUrl The root url to use to load external dependencies like texture
  56455. * @returns the Parsed particle system
  56456. */
  56457. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56458. var name = parsedParticleSystem.name;
  56459. var custom = null;
  56460. var program = null;
  56461. if (parsedParticleSystem.customShader) {
  56462. program = parsedParticleSystem.customShader;
  56463. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56464. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56465. }
  56466. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56467. particleSystem.customShader = program;
  56468. if (parsedParticleSystem.id) {
  56469. particleSystem.id = parsedParticleSystem.id;
  56470. }
  56471. // Auto start
  56472. if (parsedParticleSystem.preventAutoStart) {
  56473. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56474. }
  56475. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56476. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56477. if (!particleSystem.preventAutoStart) {
  56478. particleSystem.start();
  56479. }
  56480. return particleSystem;
  56481. };
  56482. /**
  56483. * Source color is added to the destination color without alpha affecting the result.
  56484. */
  56485. ParticleSystem.BLENDMODE_ONEONE = 0;
  56486. /**
  56487. * Blend current color and particle color using particle’s alpha.
  56488. */
  56489. ParticleSystem.BLENDMODE_STANDARD = 1;
  56490. /**
  56491. * Add current color and particle color multiplied by particle’s alpha.
  56492. */
  56493. ParticleSystem.BLENDMODE_ADD = 2;
  56494. return ParticleSystem;
  56495. }());
  56496. BABYLON.ParticleSystem = ParticleSystem;
  56497. })(BABYLON || (BABYLON = {}));
  56498. //# sourceMappingURL=babylon.particleSystem.js.map
  56499. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56500. var BABYLON;
  56501. (function (BABYLON) {
  56502. /**
  56503. * Particle emitter emitting particles from the inside of a box.
  56504. * It emits the particles randomly between 2 given directions.
  56505. */
  56506. var BoxParticleEmitter = /** @class */ (function () {
  56507. /**
  56508. * Creates a new instance BoxParticleEmitter
  56509. */
  56510. function BoxParticleEmitter() {
  56511. /**
  56512. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56513. */
  56514. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56515. /**
  56516. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56517. */
  56518. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56519. /**
  56520. * 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.
  56521. */
  56522. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56523. /**
  56524. * 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.
  56525. */
  56526. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56527. }
  56528. /**
  56529. * Called by the particle System when the direction is computed for the created particle.
  56530. * @param worldMatrix is the world matrix of the particle system
  56531. * @param directionToUpdate is the direction vector to update with the result
  56532. * @param particle is the particle we are computed the direction for
  56533. */
  56534. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56535. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56536. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56537. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56538. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56539. };
  56540. /**
  56541. * Called by the particle System when the position is computed for the created particle.
  56542. * @param worldMatrix is the world matrix of the particle system
  56543. * @param positionToUpdate is the position vector to update with the result
  56544. * @param particle is the particle we are computed the position for
  56545. */
  56546. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56547. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56548. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56549. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56550. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56551. };
  56552. /**
  56553. * Clones the current emitter and returns a copy of it
  56554. * @returns the new emitter
  56555. */
  56556. BoxParticleEmitter.prototype.clone = function () {
  56557. var newOne = new BoxParticleEmitter();
  56558. BABYLON.Tools.DeepCopy(this, newOne);
  56559. return newOne;
  56560. };
  56561. /**
  56562. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56563. * @param effect defines the update shader
  56564. */
  56565. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56566. effect.setVector3("direction1", this.direction1);
  56567. effect.setVector3("direction2", this.direction2);
  56568. effect.setVector3("minEmitBox", this.minEmitBox);
  56569. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56570. };
  56571. /**
  56572. * Returns a string to use to update the GPU particles update shader
  56573. * @returns a string containng the defines string
  56574. */
  56575. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56576. return "#define BOXEMITTER";
  56577. };
  56578. /**
  56579. * Returns the string "BoxParticleEmitter"
  56580. * @returns a string containing the class name
  56581. */
  56582. BoxParticleEmitter.prototype.getClassName = function () {
  56583. return "BoxParticleEmitter";
  56584. };
  56585. /**
  56586. * Serializes the particle system to a JSON object.
  56587. * @returns the JSON object
  56588. */
  56589. BoxParticleEmitter.prototype.serialize = function () {
  56590. var serializationObject = {};
  56591. serializationObject.type = this.getClassName();
  56592. serializationObject.direction1 = this.direction1.asArray();
  56593. serializationObject.direction2 = this.direction2.asArray();
  56594. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56595. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56596. return serializationObject;
  56597. };
  56598. /**
  56599. * Parse properties from a JSON object
  56600. * @param serializationObject defines the JSON object
  56601. */
  56602. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56603. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56604. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56605. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56606. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56607. };
  56608. return BoxParticleEmitter;
  56609. }());
  56610. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56611. })(BABYLON || (BABYLON = {}));
  56612. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56613. var BABYLON;
  56614. (function (BABYLON) {
  56615. /**
  56616. * Particle emitter emitting particles from the inside of a cone.
  56617. * It emits the particles alongside the cone volume from the base to the particle.
  56618. * The emission direction might be randomized.
  56619. */
  56620. var ConeParticleEmitter = /** @class */ (function () {
  56621. /**
  56622. * Creates a new instance ConeParticleEmitter
  56623. * @param radius the radius of the emission cone (1 by default)
  56624. * @param angles the cone base angle (PI by default)
  56625. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56626. */
  56627. function ConeParticleEmitter(radius, angle,
  56628. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56629. directionRandomizer) {
  56630. if (radius === void 0) { radius = 1; }
  56631. if (angle === void 0) { angle = Math.PI; }
  56632. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56633. this.directionRandomizer = directionRandomizer;
  56634. /**
  56635. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56636. */
  56637. this.radiusRange = 1;
  56638. /**
  56639. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56640. */
  56641. this.heightRange = 1;
  56642. this.angle = angle;
  56643. this.radius = radius;
  56644. }
  56645. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56646. /**
  56647. * Gets or sets the radius of the emission cone
  56648. */
  56649. get: function () {
  56650. return this._radius;
  56651. },
  56652. set: function (value) {
  56653. this._radius = value;
  56654. this._buildHeight();
  56655. },
  56656. enumerable: true,
  56657. configurable: true
  56658. });
  56659. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56660. /**
  56661. * Gets or sets the angle of the emission cone
  56662. */
  56663. get: function () {
  56664. return this._angle;
  56665. },
  56666. set: function (value) {
  56667. this._angle = value;
  56668. this._buildHeight();
  56669. },
  56670. enumerable: true,
  56671. configurable: true
  56672. });
  56673. ConeParticleEmitter.prototype._buildHeight = function () {
  56674. if (this._angle !== 0) {
  56675. this._height = this._radius / Math.tan(this._angle / 2);
  56676. }
  56677. else {
  56678. this._height = 1;
  56679. }
  56680. };
  56681. /**
  56682. * Called by the particle System when the direction is computed for the created particle.
  56683. * @param worldMatrix is the world matrix of the particle system
  56684. * @param directionToUpdate is the direction vector to update with the result
  56685. * @param particle is the particle we are computed the direction for
  56686. */
  56687. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56688. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56689. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56690. }
  56691. else {
  56692. // measure the direction Vector from the emitter to the particle.
  56693. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56694. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56695. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56696. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56697. direction.x += randX;
  56698. direction.y += randY;
  56699. direction.z += randZ;
  56700. direction.normalize();
  56701. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56702. }
  56703. };
  56704. /**
  56705. * Called by the particle System when the position is computed for the created particle.
  56706. * @param worldMatrix is the world matrix of the particle system
  56707. * @param positionToUpdate is the position vector to update with the result
  56708. * @param particle is the particle we are computed the position for
  56709. */
  56710. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56711. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56712. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56713. // Better distribution in a cone at normal angles.
  56714. h = 1 - h * h;
  56715. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56716. radius = radius * h;
  56717. var randX = radius * Math.sin(s);
  56718. var randZ = radius * Math.cos(s);
  56719. var randY = h * this._height;
  56720. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56721. };
  56722. /**
  56723. * Clones the current emitter and returns a copy of it
  56724. * @returns the new emitter
  56725. */
  56726. ConeParticleEmitter.prototype.clone = function () {
  56727. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56728. BABYLON.Tools.DeepCopy(this, newOne);
  56729. return newOne;
  56730. };
  56731. /**
  56732. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56733. * @param effect defines the update shader
  56734. */
  56735. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56736. effect.setFloat2("radius", this._radius, this.radiusRange);
  56737. effect.setFloat("coneAngle", this._angle);
  56738. effect.setFloat2("height", this._height, this.heightRange);
  56739. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56740. };
  56741. /**
  56742. * Returns a string to use to update the GPU particles update shader
  56743. * @returns a string containng the defines string
  56744. */
  56745. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56746. return "#define CONEEMITTER";
  56747. };
  56748. /**
  56749. * Returns the string "ConeParticleEmitter"
  56750. * @returns a string containing the class name
  56751. */
  56752. ConeParticleEmitter.prototype.getClassName = function () {
  56753. return "ConeParticleEmitter";
  56754. };
  56755. /**
  56756. * Serializes the particle system to a JSON object.
  56757. * @returns the JSON object
  56758. */
  56759. ConeParticleEmitter.prototype.serialize = function () {
  56760. var serializationObject = {};
  56761. serializationObject.type = this.getClassName();
  56762. serializationObject.radius = this._radius;
  56763. serializationObject.angle = this._angle;
  56764. serializationObject.directionRandomizer = this.directionRandomizer;
  56765. return serializationObject;
  56766. };
  56767. /**
  56768. * Parse properties from a JSON object
  56769. * @param serializationObject defines the JSON object
  56770. */
  56771. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56772. this.radius = serializationObject.radius;
  56773. this.angle = serializationObject.angle;
  56774. this.directionRandomizer = serializationObject.directionRandomizer;
  56775. };
  56776. return ConeParticleEmitter;
  56777. }());
  56778. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56779. })(BABYLON || (BABYLON = {}));
  56780. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56781. var BABYLON;
  56782. (function (BABYLON) {
  56783. /**
  56784. * Particle emitter emitting particles from the inside of a sphere.
  56785. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56786. */
  56787. var SphereParticleEmitter = /** @class */ (function () {
  56788. /**
  56789. * Creates a new instance SphereParticleEmitter
  56790. * @param radius the radius of the emission sphere (1 by default)
  56791. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56792. */
  56793. function SphereParticleEmitter(
  56794. /**
  56795. * The radius of the emission sphere.
  56796. */
  56797. radius,
  56798. /**
  56799. * How much to randomize the particle direction [0-1].
  56800. */
  56801. directionRandomizer) {
  56802. if (radius === void 0) { radius = 1; }
  56803. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56804. this.radius = radius;
  56805. this.directionRandomizer = directionRandomizer;
  56806. /**
  56807. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56808. */
  56809. this.radiusRange = 1;
  56810. }
  56811. /**
  56812. * Called by the particle System when the direction is computed for the created particle.
  56813. * @param worldMatrix is the world matrix of the particle system
  56814. * @param directionToUpdate is the direction vector to update with the result
  56815. * @param particle is the particle we are computed the direction for
  56816. */
  56817. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56818. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56819. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56820. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56821. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56822. direction.x += randX;
  56823. direction.y += randY;
  56824. direction.z += randZ;
  56825. direction.normalize();
  56826. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56827. };
  56828. /**
  56829. * Called by the particle System when the position is computed for the created particle.
  56830. * @param worldMatrix is the world matrix of the particle system
  56831. * @param positionToUpdate is the position vector to update with the result
  56832. * @param particle is the particle we are computed the position for
  56833. */
  56834. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56835. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56836. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56837. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56838. var theta = Math.acos(2 * v - 1);
  56839. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56840. var randY = randRadius * Math.cos(theta);
  56841. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56842. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56843. };
  56844. /**
  56845. * Clones the current emitter and returns a copy of it
  56846. * @returns the new emitter
  56847. */
  56848. SphereParticleEmitter.prototype.clone = function () {
  56849. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56850. BABYLON.Tools.DeepCopy(this, newOne);
  56851. return newOne;
  56852. };
  56853. /**
  56854. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56855. * @param effect defines the update shader
  56856. */
  56857. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56858. effect.setFloat("radius", this.radius);
  56859. effect.setFloat("radiusRange", this.radiusRange);
  56860. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56861. };
  56862. /**
  56863. * Returns a string to use to update the GPU particles update shader
  56864. * @returns a string containng the defines string
  56865. */
  56866. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56867. return "#define SPHEREEMITTER";
  56868. };
  56869. /**
  56870. * Returns the string "SphereParticleEmitter"
  56871. * @returns a string containing the class name
  56872. */
  56873. SphereParticleEmitter.prototype.getClassName = function () {
  56874. return "SphereParticleEmitter";
  56875. };
  56876. /**
  56877. * Serializes the particle system to a JSON object.
  56878. * @returns the JSON object
  56879. */
  56880. SphereParticleEmitter.prototype.serialize = function () {
  56881. var serializationObject = {};
  56882. serializationObject.type = this.getClassName();
  56883. serializationObject.radius = this.radius;
  56884. serializationObject.radiusRange = this.radiusRange;
  56885. serializationObject.directionRandomizer = this.directionRandomizer;
  56886. return serializationObject;
  56887. };
  56888. /**
  56889. * Parse properties from a JSON object
  56890. * @param serializationObject defines the JSON object
  56891. */
  56892. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56893. this.radius = serializationObject.radius;
  56894. this.radiusRange = serializationObject.radiusRange;
  56895. this.directionRandomizer = serializationObject.directionRandomizer;
  56896. };
  56897. return SphereParticleEmitter;
  56898. }());
  56899. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56900. /**
  56901. * Particle emitter emitting particles from the inside of a sphere.
  56902. * It emits the particles randomly between two vectors.
  56903. */
  56904. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56905. __extends(SphereDirectedParticleEmitter, _super);
  56906. /**
  56907. * Creates a new instance SphereDirectedParticleEmitter
  56908. * @param radius the radius of the emission sphere (1 by default)
  56909. * @param direction1 the min limit of the emission direction (up vector by default)
  56910. * @param direction2 the max limit of the emission direction (up vector by default)
  56911. */
  56912. function SphereDirectedParticleEmitter(radius,
  56913. /**
  56914. * The min limit of the emission direction.
  56915. */
  56916. direction1,
  56917. /**
  56918. * The max limit of the emission direction.
  56919. */
  56920. direction2) {
  56921. if (radius === void 0) { radius = 1; }
  56922. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56923. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56924. var _this = _super.call(this, radius) || this;
  56925. _this.direction1 = direction1;
  56926. _this.direction2 = direction2;
  56927. return _this;
  56928. }
  56929. /**
  56930. * Called by the particle System when the direction is computed for the created particle.
  56931. * @param worldMatrix is the world matrix of the particle system
  56932. * @param directionToUpdate is the direction vector to update with the result
  56933. * @param particle is the particle we are computed the direction for
  56934. */
  56935. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56936. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56937. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56938. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56939. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56940. };
  56941. /**
  56942. * Clones the current emitter and returns a copy of it
  56943. * @returns the new emitter
  56944. */
  56945. SphereDirectedParticleEmitter.prototype.clone = function () {
  56946. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56947. BABYLON.Tools.DeepCopy(this, newOne);
  56948. return newOne;
  56949. };
  56950. /**
  56951. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56952. * @param effect defines the update shader
  56953. */
  56954. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56955. effect.setFloat("radius", this.radius);
  56956. effect.setFloat("radiusRange", this.radiusRange);
  56957. effect.setVector3("direction1", this.direction1);
  56958. effect.setVector3("direction2", this.direction2);
  56959. };
  56960. /**
  56961. * Returns a string to use to update the GPU particles update shader
  56962. * @returns a string containng the defines string
  56963. */
  56964. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56965. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56966. };
  56967. /**
  56968. * Returns the string "SphereDirectedParticleEmitter"
  56969. * @returns a string containing the class name
  56970. */
  56971. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56972. return "SphereDirectedParticleEmitter";
  56973. };
  56974. /**
  56975. * Serializes the particle system to a JSON object.
  56976. * @returns the JSON object
  56977. */
  56978. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56979. var serializationObject = _super.prototype.serialize.call(this);
  56980. serializationObject.direction1 = this.direction1.asArray();
  56981. serializationObject.direction2 = this.direction2.asArray();
  56982. return serializationObject;
  56983. };
  56984. /**
  56985. * Parse properties from a JSON object
  56986. * @param serializationObject defines the JSON object
  56987. */
  56988. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56989. _super.prototype.parse.call(this, serializationObject);
  56990. this.direction1.copyFrom(serializationObject.direction1);
  56991. this.direction2.copyFrom(serializationObject.direction2);
  56992. };
  56993. return SphereDirectedParticleEmitter;
  56994. }(SphereParticleEmitter));
  56995. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56996. })(BABYLON || (BABYLON = {}));
  56997. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56998. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56999. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57000. s = arguments[i];
  57001. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57002. t[p] = s[p];
  57003. }
  57004. return t;
  57005. };
  57006. var BABYLON;
  57007. (function (BABYLON) {
  57008. /**
  57009. * This represents a GPU particle system in Babylon
  57010. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57011. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57012. */
  57013. var GPUParticleSystem = /** @class */ (function () {
  57014. /**
  57015. * Instantiates a GPU particle system.
  57016. * 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.
  57017. * @param name The name of the particle system
  57018. * @param options The options used to create the system
  57019. * @param scene The scene the particle system belongs to
  57020. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57021. */
  57022. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  57023. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57024. /**
  57025. * The emitter represents the Mesh or position we are attaching the particle system to.
  57026. */
  57027. this.emitter = null;
  57028. /**
  57029. * The rendering group used by the Particle system to chose when to render.
  57030. */
  57031. this.renderingGroupId = 0;
  57032. /**
  57033. * The layer mask we are rendering the particles through.
  57034. */
  57035. this.layerMask = 0x0FFFFFFF;
  57036. this._accumulatedCount = 0;
  57037. this._targetIndex = 0;
  57038. this._currentRenderId = -1;
  57039. this._started = false;
  57040. this._stopped = false;
  57041. this._timeDelta = 0;
  57042. this._attributesStrideSize = 21;
  57043. this._actualFrame = 0;
  57044. this._rawTextureWidth = 256;
  57045. /**
  57046. * List of animations used by the particle system.
  57047. */
  57048. this.animations = [];
  57049. /**
  57050. * An event triggered when the system is disposed.
  57051. */
  57052. this.onDisposeObservable = new BABYLON.Observable();
  57053. /**
  57054. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57055. */
  57056. this.updateSpeed = 0.01;
  57057. /**
  57058. * The amount of time the particle system is running (depends of the overall update speed).
  57059. */
  57060. this.targetStopDuration = 0;
  57061. /**
  57062. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57063. */
  57064. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57065. /**
  57066. * Minimum life time of emitting particles.
  57067. */
  57068. this.minLifeTime = 1;
  57069. /**
  57070. * Maximum life time of emitting particles.
  57071. */
  57072. this.maxLifeTime = 1;
  57073. /**
  57074. * Minimum Size of emitting particles.
  57075. */
  57076. this.minSize = 1;
  57077. /**
  57078. * Maximum Size of emitting particles.
  57079. */
  57080. this.maxSize = 1;
  57081. /**
  57082. * Minimum scale of emitting particles on X axis.
  57083. */
  57084. this.minScaleX = 1;
  57085. /**
  57086. * Maximum scale of emitting particles on X axis.
  57087. */
  57088. this.maxScaleX = 1;
  57089. /**
  57090. * Minimum scale of emitting particles on Y axis.
  57091. */
  57092. this.minScaleY = 1;
  57093. /**
  57094. * Maximum scale of emitting particles on Y axis.
  57095. */
  57096. this.maxScaleY = 1;
  57097. /**
  57098. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57099. */
  57100. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57101. /**
  57102. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57103. */
  57104. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57105. /**
  57106. * Color the particle will have at the end of its lifetime.
  57107. */
  57108. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57109. /**
  57110. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57111. */
  57112. this.emitRate = 100;
  57113. /**
  57114. * You can use gravity if you want to give an orientation to your particles.
  57115. */
  57116. this.gravity = BABYLON.Vector3.Zero();
  57117. /**
  57118. * Minimum power of emitting particles.
  57119. */
  57120. this.minEmitPower = 1;
  57121. /**
  57122. * Maximum power of emitting particles.
  57123. */
  57124. this.maxEmitPower = 1;
  57125. /**
  57126. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57127. */
  57128. this.minAngularSpeed = 0;
  57129. /**
  57130. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57131. */
  57132. this.maxAngularSpeed = 0;
  57133. /**
  57134. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57135. * to override the particles.
  57136. */
  57137. this.forceDepthWrite = false;
  57138. this._preWarmDone = false;
  57139. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  57140. this.preWarmCycles = 0;
  57141. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57142. this.preWarmStepOffset = 1;
  57143. /**
  57144. * Gets or sets the minimal initial rotation in radians.
  57145. */
  57146. this.minInitialRotation = 0;
  57147. /**
  57148. * Gets or sets the maximal initial rotation in radians.
  57149. */
  57150. this.maxInitialRotation = 0;
  57151. /**
  57152. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  57153. */
  57154. this.spriteCellChangeSpeed = 1;
  57155. /**
  57156. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57157. */
  57158. this.startSpriteCellID = 0;
  57159. /**
  57160. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57161. */
  57162. this.endSpriteCellID = 0;
  57163. /**
  57164. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57165. */
  57166. this.spriteCellWidth = 0;
  57167. /**
  57168. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57169. */
  57170. this.spriteCellHeight = 0;
  57171. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57172. this.translationPivot = new BABYLON.Vector2(0, 0);
  57173. /**
  57174. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57175. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  57176. */
  57177. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  57178. this._isBillboardBased = true;
  57179. this._colorGradients = null;
  57180. this._angularSpeedGradients = null;
  57181. this._sizeGradients = null;
  57182. this.id = name;
  57183. this.name = name;
  57184. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57185. this._engine = this._scene.getEngine();
  57186. if (!options.randomTextureSize) {
  57187. delete options.randomTextureSize;
  57188. }
  57189. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57190. var optionsAsNumber = options;
  57191. if (isFinite(optionsAsNumber)) {
  57192. fullOptions.capacity = optionsAsNumber;
  57193. }
  57194. this._capacity = fullOptions.capacity;
  57195. this._activeCount = fullOptions.capacity;
  57196. this._currentActiveCount = 0;
  57197. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57198. this._scene.particleSystems.push(this);
  57199. this._updateEffectOptions = {
  57200. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  57201. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57202. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57203. "angleRange", "radiusRange", "cellInfos"],
  57204. uniformBuffersNames: [],
  57205. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler"],
  57206. defines: "",
  57207. fallbacks: null,
  57208. onCompiled: null,
  57209. onError: null,
  57210. indexParameters: null,
  57211. maxSimultaneousLights: 0,
  57212. transformFeedbackVaryings: []
  57213. };
  57214. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57215. // Random data
  57216. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57217. var d = [];
  57218. for (var i = 0; i < maxTextureSize; ++i) {
  57219. d.push(Math.random());
  57220. d.push(Math.random());
  57221. d.push(Math.random());
  57222. d.push(Math.random());
  57223. }
  57224. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57225. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57226. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57227. d = [];
  57228. for (var i = 0; i < maxTextureSize; ++i) {
  57229. d.push(Math.random());
  57230. d.push(Math.random());
  57231. d.push(Math.random());
  57232. d.push(Math.random());
  57233. }
  57234. this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57235. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57236. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57237. this._randomTextureSize = maxTextureSize;
  57238. }
  57239. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57240. /**
  57241. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57242. */
  57243. get: function () {
  57244. if (!BABYLON.Engine.LastCreatedEngine) {
  57245. return false;
  57246. }
  57247. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57248. },
  57249. enumerable: true,
  57250. configurable: true
  57251. });
  57252. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57253. /**
  57254. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57255. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57256. */
  57257. get: function () {
  57258. if (this.particleEmitterType.direction1) {
  57259. return this.particleEmitterType.direction1;
  57260. }
  57261. return BABYLON.Vector3.Zero();
  57262. },
  57263. set: function (value) {
  57264. if (this.particleEmitterType.direction1) {
  57265. this.particleEmitterType.direction1 = value;
  57266. }
  57267. },
  57268. enumerable: true,
  57269. configurable: true
  57270. });
  57271. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57272. /**
  57273. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57274. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57275. */
  57276. get: function () {
  57277. if (this.particleEmitterType.direction2) {
  57278. return this.particleEmitterType.direction2;
  57279. }
  57280. return BABYLON.Vector3.Zero();
  57281. },
  57282. set: function (value) {
  57283. if (this.particleEmitterType.direction2) {
  57284. this.particleEmitterType.direction2 = value;
  57285. }
  57286. },
  57287. enumerable: true,
  57288. configurable: true
  57289. });
  57290. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57291. /**
  57292. * 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.
  57293. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57294. */
  57295. get: function () {
  57296. if (this.particleEmitterType.minEmitBox) {
  57297. return this.particleEmitterType.minEmitBox;
  57298. }
  57299. return BABYLON.Vector3.Zero();
  57300. },
  57301. set: function (value) {
  57302. if (this.particleEmitterType.minEmitBox) {
  57303. this.particleEmitterType.minEmitBox = value;
  57304. }
  57305. },
  57306. enumerable: true,
  57307. configurable: true
  57308. });
  57309. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57310. /**
  57311. * 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.
  57312. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57313. */
  57314. get: function () {
  57315. if (this.particleEmitterType.maxEmitBox) {
  57316. return this.particleEmitterType.maxEmitBox;
  57317. }
  57318. return BABYLON.Vector3.Zero();
  57319. },
  57320. set: function (value) {
  57321. if (this.particleEmitterType.maxEmitBox) {
  57322. this.particleEmitterType.maxEmitBox = value;
  57323. }
  57324. },
  57325. enumerable: true,
  57326. configurable: true
  57327. });
  57328. /**
  57329. * Gets the maximum number of particles active at the same time.
  57330. * @returns The max number of active particles.
  57331. */
  57332. GPUParticleSystem.prototype.getCapacity = function () {
  57333. return this._capacity;
  57334. };
  57335. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57336. /**
  57337. * Gets or set the number of active particles
  57338. */
  57339. get: function () {
  57340. return this._activeCount;
  57341. },
  57342. set: function (value) {
  57343. this._activeCount = Math.min(value, this._capacity);
  57344. },
  57345. enumerable: true,
  57346. configurable: true
  57347. });
  57348. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  57349. /**
  57350. * Gets whether an animation sprite sheet is enabled or not on the particle system
  57351. */
  57352. get: function () {
  57353. return this._isAnimationSheetEnabled;
  57354. },
  57355. enumerable: true,
  57356. configurable: true
  57357. });
  57358. /**
  57359. * Is this system ready to be used/rendered
  57360. * @return true if the system is ready
  57361. */
  57362. GPUParticleSystem.prototype.isReady = function () {
  57363. if (!this._updateEffect) {
  57364. this._recreateUpdateEffect();
  57365. this._recreateRenderEffect();
  57366. return false;
  57367. }
  57368. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57369. return false;
  57370. }
  57371. return true;
  57372. };
  57373. /**
  57374. * Gets Wether the system has been started.
  57375. * @returns True if it has been started, otherwise false.
  57376. */
  57377. GPUParticleSystem.prototype.isStarted = function () {
  57378. return this._started;
  57379. };
  57380. /**
  57381. * Starts the particle system and begins to emit.
  57382. */
  57383. GPUParticleSystem.prototype.start = function () {
  57384. this._started = true;
  57385. this._stopped = false;
  57386. this._preWarmDone = false;
  57387. };
  57388. /**
  57389. * Stops the particle system.
  57390. */
  57391. GPUParticleSystem.prototype.stop = function () {
  57392. this._stopped = true;
  57393. };
  57394. /**
  57395. * Remove all active particles
  57396. */
  57397. GPUParticleSystem.prototype.reset = function () {
  57398. this._releaseBuffers();
  57399. this._releaseVAOs();
  57400. this._currentActiveCount = 0;
  57401. this._targetIndex = 0;
  57402. };
  57403. /**
  57404. * Returns the string "GPUParticleSystem"
  57405. * @returns a string containing the class name
  57406. */
  57407. GPUParticleSystem.prototype.getClassName = function () {
  57408. return "GPUParticleSystem";
  57409. };
  57410. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57411. /**
  57412. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57413. */
  57414. get: function () {
  57415. return this._isBillboardBased;
  57416. },
  57417. set: function (value) {
  57418. if (this._isBillboardBased === value) {
  57419. return;
  57420. }
  57421. this._isBillboardBased = value;
  57422. this._releaseBuffers();
  57423. },
  57424. enumerable: true,
  57425. configurable: true
  57426. });
  57427. /**
  57428. * Gets the current list of color gradients.
  57429. * You must use addColorGradient and removeColorGradient to udpate this list
  57430. * @returns the list of color gradients
  57431. */
  57432. GPUParticleSystem.prototype.getColorGradients = function () {
  57433. return this._colorGradients;
  57434. };
  57435. /**
  57436. * Gets the current list of size gradients.
  57437. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57438. * @returns the list of size gradients
  57439. */
  57440. GPUParticleSystem.prototype.getSizeGradients = function () {
  57441. return this._sizeGradients;
  57442. };
  57443. /**
  57444. * Gets the current list of angular speed gradients.
  57445. * You must use addAngularSpeedGradient and removeAngularGradient to udpate this list
  57446. * @returns the list of angular speed gradients
  57447. */
  57448. GPUParticleSystem.prototype.getAngularSpeedGradients = function () {
  57449. return this._angularSpeedGradients;
  57450. };
  57451. GPUParticleSystem.prototype._removeGradient = function (gradient, gradients, texture) {
  57452. if (!gradients) {
  57453. return this;
  57454. }
  57455. var index = 0;
  57456. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  57457. var valueGradient = gradients_1[_i];
  57458. if (valueGradient.gradient === gradient) {
  57459. gradients.splice(index, 1);
  57460. break;
  57461. }
  57462. index++;
  57463. }
  57464. if (texture) {
  57465. texture.dispose();
  57466. }
  57467. this._releaseBuffers();
  57468. return this;
  57469. };
  57470. /**
  57471. * Adds a new color gradient
  57472. * @param gradient defines the gradient to use (between 0 and 1)
  57473. * @param color defines the color to affect to the specified gradient
  57474. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57475. * @returns the current particle system
  57476. */
  57477. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57478. if (!this._colorGradients) {
  57479. this._colorGradients = [];
  57480. }
  57481. var colorGradient = new BABYLON.ColorGradient();
  57482. colorGradient.gradient = gradient;
  57483. colorGradient.color1 = color1;
  57484. this._colorGradients.push(colorGradient);
  57485. this._colorGradients.sort(function (a, b) {
  57486. if (a.gradient < b.gradient) {
  57487. return -1;
  57488. }
  57489. else if (a.gradient > b.gradient) {
  57490. return 1;
  57491. }
  57492. return 0;
  57493. });
  57494. if (this._colorGradientsTexture) {
  57495. this._colorGradientsTexture.dispose();
  57496. this._colorGradientsTexture = null;
  57497. }
  57498. this._releaseBuffers();
  57499. return this;
  57500. };
  57501. /**
  57502. * Remove a specific color gradient
  57503. * @param gradient defines the gradient to remove
  57504. * @returns the current particle system
  57505. */
  57506. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57507. this._removeGradient(gradient, this._colorGradients, this._colorGradientsTexture);
  57508. this._colorGradientsTexture = null;
  57509. return this;
  57510. };
  57511. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  57512. var valueGradient = new BABYLON.FactorGradient();
  57513. valueGradient.gradient = gradient;
  57514. valueGradient.factor1 = factor;
  57515. factorGradients.push(valueGradient);
  57516. factorGradients.sort(function (a, b) {
  57517. if (a.gradient < b.gradient) {
  57518. return -1;
  57519. }
  57520. else if (a.gradient > b.gradient) {
  57521. return 1;
  57522. }
  57523. return 0;
  57524. });
  57525. this._releaseBuffers();
  57526. };
  57527. /**
  57528. * Adds a new size gradient
  57529. * @param gradient defines the gradient to use (between 0 and 1)
  57530. * @param factor defines the size factor to affect to the specified gradient
  57531. * @returns the current particle system
  57532. */
  57533. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57534. if (!this._sizeGradients) {
  57535. this._sizeGradients = [];
  57536. }
  57537. this._addFactorGradient(this._sizeGradients, gradient, factor);
  57538. if (this._sizeGradientsTexture) {
  57539. this._sizeGradientsTexture.dispose();
  57540. this._sizeGradientsTexture = null;
  57541. }
  57542. this._releaseBuffers();
  57543. return this;
  57544. };
  57545. /**
  57546. * Remove a specific size gradient
  57547. * @param gradient defines the gradient to remove
  57548. * @returns the current particle system
  57549. */
  57550. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57551. this._removeGradient(gradient, this._sizeGradients, this._sizeGradientsTexture);
  57552. this._sizeGradientsTexture = null;
  57553. return this;
  57554. };
  57555. /**
  57556. * Adds a new angular speed gradient
  57557. * @param gradient defines the gradient to use (between 0 and 1)
  57558. * @param factor defines the size factor to affect to the specified gradient
  57559. * @returns the current particle system
  57560. */
  57561. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  57562. if (!this._angularSpeedGradients) {
  57563. this._angularSpeedGradients = [];
  57564. }
  57565. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  57566. if (this._angularSpeedGradientsTexture) {
  57567. this._angularSpeedGradientsTexture.dispose();
  57568. this._angularSpeedGradientsTexture = null;
  57569. }
  57570. this._releaseBuffers();
  57571. return this;
  57572. };
  57573. /**
  57574. * Remove a specific angular speed gradient
  57575. * @param gradient defines the gradient to remove
  57576. * @returns the current particle system
  57577. */
  57578. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  57579. this._removeGradient(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  57580. this._angularSpeedGradientsTexture = null;
  57581. return this;
  57582. };
  57583. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57584. var updateVertexBuffers = {};
  57585. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57586. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57587. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57588. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57589. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57590. var offset = 12;
  57591. if (!this._colorGradientsTexture) {
  57592. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57593. offset += 4;
  57594. }
  57595. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57596. offset += 3;
  57597. if (!this._isBillboardBased) {
  57598. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57599. offset += 3;
  57600. }
  57601. if (this._angularSpeedGradientsTexture) {
  57602. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  57603. offset += 1;
  57604. }
  57605. else {
  57606. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57607. offset += 2;
  57608. }
  57609. if (this._isAnimationSheetEnabled) {
  57610. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  57611. offset += 1;
  57612. }
  57613. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57614. this._engine.bindArrayBuffer(null);
  57615. return vao;
  57616. };
  57617. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57618. var renderVertexBuffers = {};
  57619. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57620. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57621. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57622. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57623. var offset = 12;
  57624. if (!this._colorGradientsTexture) {
  57625. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57626. offset += 4;
  57627. }
  57628. offset += 3; // Direction
  57629. if (!this._isBillboardBased) {
  57630. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57631. offset += 3;
  57632. }
  57633. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  57634. if (this._angularSpeedGradientsTexture) {
  57635. offset++;
  57636. }
  57637. else {
  57638. offset += 2;
  57639. }
  57640. if (this._isAnimationSheetEnabled) {
  57641. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  57642. offset += 1;
  57643. }
  57644. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57645. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57646. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57647. this._engine.bindArrayBuffer(null);
  57648. return vao;
  57649. };
  57650. GPUParticleSystem.prototype._initialize = function (force) {
  57651. if (force === void 0) { force = false; }
  57652. if (this._buffer0 && !force) {
  57653. return;
  57654. }
  57655. var engine = this._scene.getEngine();
  57656. var data = new Array();
  57657. if (!this.isBillboardBased) {
  57658. this._attributesStrideSize += 3;
  57659. }
  57660. if (this._colorGradientsTexture) {
  57661. this._attributesStrideSize -= 4;
  57662. }
  57663. if (this._angularSpeedGradientsTexture) {
  57664. this._attributesStrideSize -= 1;
  57665. }
  57666. if (this._isAnimationSheetEnabled) {
  57667. this._attributesStrideSize += 1;
  57668. }
  57669. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57670. // position
  57671. data.push(0.0);
  57672. data.push(0.0);
  57673. data.push(0.0);
  57674. // Age and life
  57675. data.push(0.0); // create the particle as a dead one to create a new one at start
  57676. data.push(0.0);
  57677. // Seed
  57678. data.push(Math.random());
  57679. data.push(Math.random());
  57680. data.push(Math.random());
  57681. data.push(Math.random());
  57682. // Size
  57683. data.push(0.0);
  57684. data.push(0.0);
  57685. data.push(0.0);
  57686. if (!this._colorGradientsTexture) {
  57687. // color
  57688. data.push(0.0);
  57689. data.push(0.0);
  57690. data.push(0.0);
  57691. data.push(0.0);
  57692. }
  57693. // direction
  57694. data.push(0.0);
  57695. data.push(0.0);
  57696. data.push(0.0);
  57697. if (!this.isBillboardBased) {
  57698. // initialDirection
  57699. data.push(0.0);
  57700. data.push(0.0);
  57701. data.push(0.0);
  57702. }
  57703. // angle
  57704. data.push(0.0);
  57705. if (!this._angularSpeedGradientsTexture) {
  57706. data.push(0.0);
  57707. }
  57708. if (this._isAnimationSheetEnabled) {
  57709. data.push(0.0);
  57710. }
  57711. }
  57712. // Sprite data
  57713. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57714. -0.5, 0.5, 0, 1,
  57715. -0.5, -0.5, 0, 0,
  57716. 0.5, -0.5, 1, 0]);
  57717. // Buffers
  57718. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57719. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57720. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57721. // Update VAO
  57722. this._updateVAO = [];
  57723. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57724. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57725. // Render VAO
  57726. this._renderVAO = [];
  57727. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57728. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57729. // Links
  57730. this._sourceBuffer = this._buffer0;
  57731. this._targetBuffer = this._buffer1;
  57732. };
  57733. /** @hidden */
  57734. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57735. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57736. if (this._isBillboardBased) {
  57737. defines += "\n#define BILLBOARD";
  57738. }
  57739. if (this._colorGradientsTexture) {
  57740. defines += "\n#define COLORGRADIENTS";
  57741. }
  57742. if (this._sizeGradientsTexture) {
  57743. defines += "\n#define SIZEGRADIENTS";
  57744. }
  57745. if (this._angularSpeedGradientsTexture) {
  57746. defines += "\n#define ANGULARSPEEDGRADIENTS";
  57747. }
  57748. if (this.isAnimationSheetEnabled) {
  57749. defines += "\n#define ANIMATESHEET";
  57750. }
  57751. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57752. return;
  57753. }
  57754. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57755. if (!this._colorGradientsTexture) {
  57756. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57757. }
  57758. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57759. if (!this._isBillboardBased) {
  57760. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57761. }
  57762. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57763. if (this.isAnimationSheetEnabled) {
  57764. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  57765. }
  57766. this._updateEffectOptions.defines = defines;
  57767. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57768. };
  57769. /** @hidden */
  57770. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57771. var defines = "";
  57772. if (this._scene.clipPlane) {
  57773. defines = "\n#define CLIPPLANE";
  57774. }
  57775. if (this._isBillboardBased) {
  57776. defines += "\n#define BILLBOARD";
  57777. switch (this.billboardMode) {
  57778. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57779. defines += "\n#define BILLBOARDY";
  57780. break;
  57781. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57782. default:
  57783. break;
  57784. }
  57785. }
  57786. if (this._colorGradientsTexture) {
  57787. defines += "\n#define COLORGRADIENTS";
  57788. }
  57789. if (this.isAnimationSheetEnabled) {
  57790. defines += "\n#define ANIMATESHEET";
  57791. }
  57792. if (this._renderEffect && this._renderEffect.defines === defines) {
  57793. return;
  57794. }
  57795. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57796. };
  57797. /**
  57798. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57799. * @param preWarm defines if we are in the pre-warmimg phase
  57800. */
  57801. GPUParticleSystem.prototype.animate = function (preWarm) {
  57802. if (preWarm === void 0) { preWarm = false; }
  57803. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57804. this._actualFrame += this._timeDelta;
  57805. if (!this._stopped) {
  57806. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57807. this.stop();
  57808. }
  57809. }
  57810. };
  57811. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  57812. var texture = this[textureName];
  57813. if (!factorGradients || !factorGradients.length || texture) {
  57814. return;
  57815. }
  57816. var data = new Float32Array(this._rawTextureWidth);
  57817. for (var x = 0; x < this._rawTextureWidth; x++) {
  57818. var ratio = x / this._rawTextureWidth;
  57819. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  57820. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57821. });
  57822. }
  57823. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57824. };
  57825. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57826. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  57827. };
  57828. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  57829. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  57830. };
  57831. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57832. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57833. return;
  57834. }
  57835. var data = new Uint8Array(this._rawTextureWidth * 4);
  57836. var tmpColor = BABYLON.Tmp.Color4[0];
  57837. for (var x = 0; x < this._rawTextureWidth; x++) {
  57838. var ratio = x / this._rawTextureWidth;
  57839. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57840. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  57841. data[x * 4] = tmpColor.r * 255;
  57842. data[x * 4 + 1] = tmpColor.g * 255;
  57843. data[x * 4 + 2] = tmpColor.b * 255;
  57844. data[x * 4 + 3] = tmpColor.a * 255;
  57845. });
  57846. }
  57847. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57848. };
  57849. /**
  57850. * Renders the particle system in its current state
  57851. * @param preWarm defines if the system should only update the particles but not render them
  57852. * @returns the current number of particles
  57853. */
  57854. GPUParticleSystem.prototype.render = function (preWarm) {
  57855. if (preWarm === void 0) { preWarm = false; }
  57856. if (!this._started) {
  57857. return 0;
  57858. }
  57859. this._createColorGradientTexture();
  57860. this._createSizeGradientTexture();
  57861. this._createAngularSpeedGradientTexture();
  57862. this._recreateUpdateEffect();
  57863. this._recreateRenderEffect();
  57864. if (!this.isReady()) {
  57865. return 0;
  57866. }
  57867. if (!preWarm) {
  57868. if (!this._preWarmDone && this.preWarmCycles) {
  57869. for (var index = 0; index < this.preWarmCycles; index++) {
  57870. this.animate(true);
  57871. this.render(true);
  57872. }
  57873. this._preWarmDone = true;
  57874. }
  57875. if (this._currentRenderId === this._scene.getRenderId()) {
  57876. return 0;
  57877. }
  57878. this._currentRenderId = this._scene.getRenderId();
  57879. }
  57880. // Get everything ready to render
  57881. this._initialize();
  57882. this._accumulatedCount += this.emitRate * this._timeDelta;
  57883. if (this._accumulatedCount > 1) {
  57884. var intPart = this._accumulatedCount | 0;
  57885. this._accumulatedCount -= intPart;
  57886. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57887. }
  57888. if (!this._currentActiveCount) {
  57889. return 0;
  57890. }
  57891. // Enable update effect
  57892. this._engine.enableEffect(this._updateEffect);
  57893. this._engine.setState(false);
  57894. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57895. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57896. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57897. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57898. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57899. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57900. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57901. if (!this._colorGradientsTexture) {
  57902. this._updateEffect.setDirectColor4("color1", this.color1);
  57903. this._updateEffect.setDirectColor4("color2", this.color2);
  57904. }
  57905. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57906. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57907. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57908. this._updateEffect.setVector3("gravity", this.gravity);
  57909. if (this._sizeGradientsTexture) {
  57910. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57911. }
  57912. if (this._angularSpeedGradientsTexture) {
  57913. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  57914. }
  57915. if (this.particleEmitterType) {
  57916. this.particleEmitterType.applyToShader(this._updateEffect);
  57917. }
  57918. if (this._isAnimationSheetEnabled) {
  57919. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  57920. }
  57921. var emitterWM;
  57922. if (this.emitter.position) {
  57923. var emitterMesh = this.emitter;
  57924. emitterWM = emitterMesh.getWorldMatrix();
  57925. }
  57926. else {
  57927. var emitterPosition = this.emitter;
  57928. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57929. }
  57930. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57931. // Bind source VAO
  57932. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57933. // Update
  57934. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57935. this._engine.setRasterizerState(false);
  57936. this._engine.beginTransformFeedback();
  57937. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57938. this._engine.endTransformFeedback();
  57939. this._engine.setRasterizerState(true);
  57940. this._engine.bindTransformFeedbackBuffer(null);
  57941. if (!preWarm) {
  57942. // Enable render effect
  57943. this._engine.enableEffect(this._renderEffect);
  57944. var viewMatrix = this._scene.getViewMatrix();
  57945. this._renderEffect.setMatrix("view", viewMatrix);
  57946. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57947. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57948. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  57949. if (this._colorGradientsTexture) {
  57950. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57951. }
  57952. else {
  57953. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57954. }
  57955. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57956. var baseSize = this.particleTexture.getBaseSize();
  57957. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57958. }
  57959. if (this._isBillboardBased) {
  57960. var camera = this._scene.activeCamera;
  57961. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  57962. }
  57963. if (this._scene.clipPlane) {
  57964. var clipPlane = this._scene.clipPlane;
  57965. var invView = viewMatrix.clone();
  57966. invView.invert();
  57967. this._renderEffect.setMatrix("invView", invView);
  57968. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57969. }
  57970. // Draw order
  57971. switch (this.blendMode) {
  57972. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57973. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57974. break;
  57975. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57976. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57977. break;
  57978. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57979. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57980. break;
  57981. }
  57982. if (this.forceDepthWrite) {
  57983. this._engine.setDepthWrite(true);
  57984. }
  57985. // Bind source VAO
  57986. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57987. // Render
  57988. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57989. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57990. }
  57991. // Switch VAOs
  57992. this._targetIndex++;
  57993. if (this._targetIndex === 2) {
  57994. this._targetIndex = 0;
  57995. }
  57996. // Switch buffers
  57997. var tmpBuffer = this._sourceBuffer;
  57998. this._sourceBuffer = this._targetBuffer;
  57999. this._targetBuffer = tmpBuffer;
  58000. return this._currentActiveCount;
  58001. };
  58002. /**
  58003. * Rebuilds the particle system
  58004. */
  58005. GPUParticleSystem.prototype.rebuild = function () {
  58006. this._initialize(true);
  58007. };
  58008. GPUParticleSystem.prototype._releaseBuffers = function () {
  58009. if (this._buffer0) {
  58010. this._buffer0.dispose();
  58011. this._buffer0 = null;
  58012. }
  58013. if (this._buffer1) {
  58014. this._buffer1.dispose();
  58015. this._buffer1 = null;
  58016. }
  58017. if (this._spriteBuffer) {
  58018. this._spriteBuffer.dispose();
  58019. this._spriteBuffer = null;
  58020. }
  58021. };
  58022. GPUParticleSystem.prototype._releaseVAOs = function () {
  58023. if (!this._updateVAO) {
  58024. return;
  58025. }
  58026. for (var index = 0; index < this._updateVAO.length; index++) {
  58027. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58028. }
  58029. this._updateVAO = [];
  58030. for (var index = 0; index < this._renderVAO.length; index++) {
  58031. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58032. }
  58033. this._renderVAO = [];
  58034. };
  58035. /**
  58036. * Disposes the particle system and free the associated resources
  58037. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58038. */
  58039. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58040. if (disposeTexture === void 0) { disposeTexture = true; }
  58041. var index = this._scene.particleSystems.indexOf(this);
  58042. if (index > -1) {
  58043. this._scene.particleSystems.splice(index, 1);
  58044. }
  58045. this._releaseBuffers();
  58046. this._releaseVAOs();
  58047. if (this._colorGradientsTexture) {
  58048. this._colorGradientsTexture.dispose();
  58049. this._colorGradientsTexture = null;
  58050. }
  58051. if (this._sizeGradientsTexture) {
  58052. this._sizeGradientsTexture.dispose();
  58053. this._sizeGradientsTexture = null;
  58054. }
  58055. if (this._angularSpeedGradientsTexture) {
  58056. this._angularSpeedGradientsTexture.dispose();
  58057. this._angularSpeedGradientsTexture = null;
  58058. }
  58059. if (this._randomTexture) {
  58060. this._randomTexture.dispose();
  58061. this._randomTexture = null;
  58062. }
  58063. if (this._randomTexture2) {
  58064. this._randomTexture2.dispose();
  58065. this._randomTexture2 = null;
  58066. }
  58067. if (disposeTexture && this.particleTexture) {
  58068. this.particleTexture.dispose();
  58069. this.particleTexture = null;
  58070. }
  58071. // Callback
  58072. this.onDisposeObservable.notifyObservers(this);
  58073. this.onDisposeObservable.clear();
  58074. };
  58075. /**
  58076. * Clones the particle system.
  58077. * @param name The name of the cloned object
  58078. * @param newEmitter The new emitter to use
  58079. * @returns the cloned particle system
  58080. */
  58081. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58082. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58083. BABYLON.Tools.DeepCopy(this, result);
  58084. if (newEmitter === undefined) {
  58085. newEmitter = this.emitter;
  58086. }
  58087. result.emitter = newEmitter;
  58088. if (this.particleTexture) {
  58089. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58090. }
  58091. return result;
  58092. };
  58093. /**
  58094. * Serializes the particle system to a JSON object.
  58095. * @returns the JSON object
  58096. */
  58097. GPUParticleSystem.prototype.serialize = function () {
  58098. var serializationObject = {};
  58099. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  58100. serializationObject.activeParticleCount = this.activeParticleCount;
  58101. return serializationObject;
  58102. };
  58103. /**
  58104. * Parses a JSON object to create a GPU particle system.
  58105. * @param parsedParticleSystem The JSON object to parse
  58106. * @param scene The scene to create the particle system in
  58107. * @param rootUrl The root url to use to load external dependencies like texture
  58108. * @returns the parsed GPU particle system
  58109. */
  58110. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58111. var name = parsedParticleSystem.name;
  58112. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58113. if (parsedParticleSystem.activeParticleCount) {
  58114. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58115. }
  58116. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58117. return particleSystem;
  58118. };
  58119. return GPUParticleSystem;
  58120. }());
  58121. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58122. })(BABYLON || (BABYLON = {}));
  58123. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58124. var BABYLON;
  58125. (function (BABYLON) {
  58126. /**
  58127. * Represents one particle of a solid particle system.
  58128. */
  58129. var SolidParticle = /** @class */ (function () {
  58130. /**
  58131. * Creates a Solid Particle object.
  58132. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58133. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58134. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58135. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58136. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58137. * @param shapeId (integer) is the model shape identifier in the SPS.
  58138. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58139. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58140. */
  58141. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58142. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58143. /**
  58144. * particle global index
  58145. */
  58146. this.idx = 0;
  58147. /**
  58148. * The color of the particle
  58149. */
  58150. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58151. /**
  58152. * The world space position of the particle.
  58153. */
  58154. this.position = BABYLON.Vector3.Zero();
  58155. /**
  58156. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58157. */
  58158. this.rotation = BABYLON.Vector3.Zero();
  58159. /**
  58160. * The scaling of the particle.
  58161. */
  58162. this.scaling = BABYLON.Vector3.One();
  58163. /**
  58164. * The uvs of the particle.
  58165. */
  58166. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58167. /**
  58168. * The current speed of the particle.
  58169. */
  58170. this.velocity = BABYLON.Vector3.Zero();
  58171. /**
  58172. * The pivot point in the particle local space.
  58173. */
  58174. this.pivot = BABYLON.Vector3.Zero();
  58175. /**
  58176. * Must the particle be translated from its pivot point in its local space ?
  58177. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58178. * Default : false
  58179. */
  58180. this.translateFromPivot = false;
  58181. /**
  58182. * Is the particle active or not ?
  58183. */
  58184. this.alive = true;
  58185. /**
  58186. * Is the particle visible or not ?
  58187. */
  58188. this.isVisible = true;
  58189. /**
  58190. * Index of this particle in the global "positions" array (Internal use)
  58191. */
  58192. this._pos = 0;
  58193. /**
  58194. * Index of this particle in the global "indices" array (Internal use)
  58195. */
  58196. this._ind = 0;
  58197. /**
  58198. * ModelShape id of this particle
  58199. */
  58200. this.shapeId = 0;
  58201. /**
  58202. * Index of the particle in its shape id (Internal use)
  58203. */
  58204. this.idxInShape = 0;
  58205. /**
  58206. * Still set as invisible in order to skip useless computations (Internal use)
  58207. */
  58208. this._stillInvisible = false;
  58209. /**
  58210. * Last computed particle rotation matrix
  58211. */
  58212. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58213. /**
  58214. * Parent particle Id, if any.
  58215. * Default null.
  58216. */
  58217. this.parentId = null;
  58218. /**
  58219. * Internal global position in the SPS.
  58220. */
  58221. this._globalPosition = BABYLON.Vector3.Zero();
  58222. this.idx = particleIndex;
  58223. this._pos = positionIndex;
  58224. this._ind = indiceIndex;
  58225. this._model = model;
  58226. this.shapeId = shapeId;
  58227. this.idxInShape = idxInShape;
  58228. this._sps = sps;
  58229. if (modelBoundingInfo) {
  58230. this._modelBoundingInfo = modelBoundingInfo;
  58231. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58232. }
  58233. }
  58234. Object.defineProperty(SolidParticle.prototype, "scale", {
  58235. /**
  58236. * Legacy support, changed scale to scaling
  58237. */
  58238. get: function () {
  58239. return this.scaling;
  58240. },
  58241. /**
  58242. * Legacy support, changed scale to scaling
  58243. */
  58244. set: function (scale) {
  58245. this.scaling = scale;
  58246. },
  58247. enumerable: true,
  58248. configurable: true
  58249. });
  58250. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58251. /**
  58252. * Legacy support, changed quaternion to rotationQuaternion
  58253. */
  58254. get: function () {
  58255. return this.rotationQuaternion;
  58256. },
  58257. /**
  58258. * Legacy support, changed quaternion to rotationQuaternion
  58259. */
  58260. set: function (q) {
  58261. this.rotationQuaternion = q;
  58262. },
  58263. enumerable: true,
  58264. configurable: true
  58265. });
  58266. /**
  58267. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58268. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58269. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58270. * @returns true if it intersects
  58271. */
  58272. SolidParticle.prototype.intersectsMesh = function (target) {
  58273. if (!this._boundingInfo || !target._boundingInfo) {
  58274. return false;
  58275. }
  58276. if (this._sps._bSphereOnly) {
  58277. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58278. }
  58279. return this._boundingInfo.intersects(target._boundingInfo, false);
  58280. };
  58281. return SolidParticle;
  58282. }());
  58283. BABYLON.SolidParticle = SolidParticle;
  58284. /**
  58285. * Represents the shape of the model used by one particle of a solid particle system.
  58286. * SPS internal tool, don't use it manually.
  58287. */
  58288. var ModelShape = /** @class */ (function () {
  58289. /**
  58290. * 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.
  58291. * SPS internal tool, don't use it manually.
  58292. * @hidden
  58293. */
  58294. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58295. /**
  58296. * length of the shape in the model indices array (internal use)
  58297. */
  58298. this._indicesLength = 0;
  58299. this.shapeID = id;
  58300. this._shape = shape;
  58301. this._indicesLength = indicesLength;
  58302. this._shapeUV = shapeUV;
  58303. this._positionFunction = posFunction;
  58304. this._vertexFunction = vtxFunction;
  58305. }
  58306. return ModelShape;
  58307. }());
  58308. BABYLON.ModelShape = ModelShape;
  58309. /**
  58310. * Represents a Depth Sorted Particle in the solid particle system.
  58311. */
  58312. var DepthSortedParticle = /** @class */ (function () {
  58313. function DepthSortedParticle() {
  58314. /**
  58315. * Index of the particle in the "indices" array
  58316. */
  58317. this.ind = 0;
  58318. /**
  58319. * Length of the particle shape in the "indices" array
  58320. */
  58321. this.indicesLength = 0;
  58322. /**
  58323. * Squared distance from the particle to the camera
  58324. */
  58325. this.sqDistance = 0.0;
  58326. }
  58327. return DepthSortedParticle;
  58328. }());
  58329. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58330. })(BABYLON || (BABYLON = {}));
  58331. //# sourceMappingURL=babylon.solidParticle.js.map
  58332. var BABYLON;
  58333. (function (BABYLON) {
  58334. /**
  58335. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58336. *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.
  58337. * The SPS is also a particle system. It provides some methods to manage the particles.
  58338. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58339. *
  58340. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58341. */
  58342. var SolidParticleSystem = /** @class */ (function () {
  58343. /**
  58344. * Creates a SPS (Solid Particle System) object.
  58345. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58346. * @param scene (Scene) is the scene in which the SPS is added.
  58347. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58348. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58349. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58350. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58351. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58352. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58353. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58354. */
  58355. function SolidParticleSystem(name, scene, options) {
  58356. /**
  58357. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58358. * Example : var p = SPS.particles[i];
  58359. */
  58360. this.particles = new Array();
  58361. /**
  58362. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58363. */
  58364. this.nbParticles = 0;
  58365. /**
  58366. * If the particles must ever face the camera (default false). Useful for planar particles.
  58367. */
  58368. this.billboard = false;
  58369. /**
  58370. * Recompute normals when adding a shape
  58371. */
  58372. this.recomputeNormals = true;
  58373. /**
  58374. * This a counter ofr your own usage. It's not set by any SPS functions.
  58375. */
  58376. this.counter = 0;
  58377. /**
  58378. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58379. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58380. */
  58381. this.vars = {};
  58382. /**
  58383. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58384. */
  58385. this._bSphereOnly = false;
  58386. /**
  58387. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58388. */
  58389. this._bSphereRadiusFactor = 1.0;
  58390. this._positions = new Array();
  58391. this._indices = new Array();
  58392. this._normals = new Array();
  58393. this._colors = new Array();
  58394. this._uvs = new Array();
  58395. this._index = 0; // indices index
  58396. this._updatable = true;
  58397. this._pickable = false;
  58398. this._isVisibilityBoxLocked = false;
  58399. this._alwaysVisible = false;
  58400. this._depthSort = false;
  58401. this._shapeCounter = 0;
  58402. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58403. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58404. this._computeParticleColor = true;
  58405. this._computeParticleTexture = true;
  58406. this._computeParticleRotation = true;
  58407. this._computeParticleVertex = false;
  58408. this._computeBoundingBox = false;
  58409. this._depthSortParticles = true;
  58410. this._cam_axisZ = BABYLON.Vector3.Zero();
  58411. this._cam_axisY = BABYLON.Vector3.Zero();
  58412. this._cam_axisX = BABYLON.Vector3.Zero();
  58413. this._axisZ = BABYLON.Axis.Z;
  58414. this._camDir = BABYLON.Vector3.Zero();
  58415. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58416. this._rotMatrix = new BABYLON.Matrix();
  58417. this._invertMatrix = new BABYLON.Matrix();
  58418. this._rotated = BABYLON.Vector3.Zero();
  58419. this._quaternion = new BABYLON.Quaternion();
  58420. this._vertex = BABYLON.Vector3.Zero();
  58421. this._normal = BABYLON.Vector3.Zero();
  58422. this._yaw = 0.0;
  58423. this._pitch = 0.0;
  58424. this._roll = 0.0;
  58425. this._halfroll = 0.0;
  58426. this._halfpitch = 0.0;
  58427. this._halfyaw = 0.0;
  58428. this._sinRoll = 0.0;
  58429. this._cosRoll = 0.0;
  58430. this._sinPitch = 0.0;
  58431. this._cosPitch = 0.0;
  58432. this._sinYaw = 0.0;
  58433. this._cosYaw = 0.0;
  58434. this._mustUnrotateFixedNormals = false;
  58435. this._minimum = BABYLON.Vector3.Zero();
  58436. this._maximum = BABYLON.Vector3.Zero();
  58437. this._minBbox = BABYLON.Vector3.Zero();
  58438. this._maxBbox = BABYLON.Vector3.Zero();
  58439. this._particlesIntersect = false;
  58440. this._depthSortFunction = function (p1, p2) {
  58441. return (p2.sqDistance - p1.sqDistance);
  58442. };
  58443. this._needs32Bits = false;
  58444. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58445. this._scaledPivot = BABYLON.Vector3.Zero();
  58446. this._particleHasParent = false;
  58447. this.name = name;
  58448. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58449. this._camera = scene.activeCamera;
  58450. this._pickable = options ? options.isPickable : false;
  58451. this._depthSort = options ? options.enableDepthSort : false;
  58452. this._particlesIntersect = options ? options.particleIntersection : false;
  58453. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58454. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58455. if (options && options.updatable !== undefined) {
  58456. this._updatable = options.updatable;
  58457. }
  58458. else {
  58459. this._updatable = true;
  58460. }
  58461. if (this._pickable) {
  58462. this.pickedParticles = [];
  58463. }
  58464. if (this._depthSort) {
  58465. this.depthSortedParticles = [];
  58466. }
  58467. }
  58468. /**
  58469. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58470. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58471. * @returns the created mesh
  58472. */
  58473. SolidParticleSystem.prototype.buildMesh = function () {
  58474. if (this.nbParticles === 0) {
  58475. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58476. this.addShape(triangle, 1);
  58477. triangle.dispose();
  58478. }
  58479. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58480. this._positions32 = new Float32Array(this._positions);
  58481. this._uvs32 = new Float32Array(this._uvs);
  58482. this._colors32 = new Float32Array(this._colors);
  58483. if (this.recomputeNormals) {
  58484. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58485. }
  58486. this._normals32 = new Float32Array(this._normals);
  58487. this._fixedNormal32 = new Float32Array(this._normals);
  58488. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58489. this._unrotateFixedNormals();
  58490. }
  58491. var vertexData = new BABYLON.VertexData();
  58492. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58493. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58494. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58495. if (this._uvs32.length > 0) {
  58496. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58497. }
  58498. if (this._colors32.length > 0) {
  58499. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58500. }
  58501. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58502. vertexData.applyToMesh(mesh, this._updatable);
  58503. this.mesh = mesh;
  58504. this.mesh.isPickable = this._pickable;
  58505. // free memory
  58506. if (!this._depthSort) {
  58507. this._indices = null;
  58508. }
  58509. this._positions = null;
  58510. this._normals = null;
  58511. this._uvs = null;
  58512. this._colors = null;
  58513. if (!this._updatable) {
  58514. this.particles.length = 0;
  58515. }
  58516. return mesh;
  58517. };
  58518. /**
  58519. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58520. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58521. * Thus the particles generated from `digest()` have their property `position` set yet.
  58522. * @param mesh ( Mesh ) is the mesh to be digested
  58523. * @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
  58524. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58525. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58526. * @returns the current SPS
  58527. */
  58528. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58529. var size = (options && options.facetNb) || 1;
  58530. var number = (options && options.number) || 0;
  58531. var delta = (options && options.delta) || 0;
  58532. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58533. var meshInd = mesh.getIndices();
  58534. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58535. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58536. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58537. var f = 0; // facet counter
  58538. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58539. // compute size from number
  58540. if (number) {
  58541. number = (number > totalFacets) ? totalFacets : number;
  58542. size = Math.round(totalFacets / number);
  58543. delta = 0;
  58544. }
  58545. else {
  58546. size = (size > totalFacets) ? totalFacets : size;
  58547. }
  58548. var facetPos = []; // submesh positions
  58549. var facetInd = []; // submesh indices
  58550. var facetUV = []; // submesh UV
  58551. var facetCol = []; // submesh colors
  58552. var barycenter = BABYLON.Vector3.Zero();
  58553. var sizeO = size;
  58554. while (f < totalFacets) {
  58555. size = sizeO + Math.floor((1 + delta) * Math.random());
  58556. if (f > totalFacets - size) {
  58557. size = totalFacets - f;
  58558. }
  58559. // reset temp arrays
  58560. facetPos.length = 0;
  58561. facetInd.length = 0;
  58562. facetUV.length = 0;
  58563. facetCol.length = 0;
  58564. // iterate over "size" facets
  58565. var fi = 0;
  58566. for (var j = f * 3; j < (f + size) * 3; j++) {
  58567. facetInd.push(fi);
  58568. var i = meshInd[j];
  58569. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58570. if (meshUV) {
  58571. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58572. }
  58573. if (meshCol) {
  58574. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58575. }
  58576. fi++;
  58577. }
  58578. // create a model shape for each single particle
  58579. var idx = this.nbParticles;
  58580. var shape = this._posToShape(facetPos);
  58581. var shapeUV = this._uvsToShapeUV(facetUV);
  58582. // compute the barycenter of the shape
  58583. var v;
  58584. for (v = 0; v < shape.length; v++) {
  58585. barycenter.addInPlace(shape[v]);
  58586. }
  58587. barycenter.scaleInPlace(1 / shape.length);
  58588. // shift the shape from its barycenter to the origin
  58589. for (v = 0; v < shape.length; v++) {
  58590. shape[v].subtractInPlace(barycenter);
  58591. }
  58592. var bInfo;
  58593. if (this._particlesIntersect) {
  58594. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58595. }
  58596. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58597. // add the particle in the SPS
  58598. var currentPos = this._positions.length;
  58599. var currentInd = this._indices.length;
  58600. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58601. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58602. // initialize the particle position
  58603. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58604. this._index += shape.length;
  58605. idx++;
  58606. this.nbParticles++;
  58607. this._shapeCounter++;
  58608. f += size;
  58609. }
  58610. return this;
  58611. };
  58612. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58613. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58614. var index = 0;
  58615. var idx = 0;
  58616. for (var p = 0; p < this.particles.length; p++) {
  58617. this._particle = this.particles[p];
  58618. this._shape = this._particle._model._shape;
  58619. if (this._particle.rotationQuaternion) {
  58620. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58621. }
  58622. else {
  58623. this._yaw = this._particle.rotation.y;
  58624. this._pitch = this._particle.rotation.x;
  58625. this._roll = this._particle.rotation.z;
  58626. this._quaternionRotationYPR();
  58627. }
  58628. this._quaternionToRotationMatrix();
  58629. this._rotMatrix.invertToRef(this._invertMatrix);
  58630. for (var pt = 0; pt < this._shape.length; pt++) {
  58631. idx = index + pt * 3;
  58632. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58633. this._fixedNormal32[idx] = this._normal.x;
  58634. this._fixedNormal32[idx + 1] = this._normal.y;
  58635. this._fixedNormal32[idx + 2] = this._normal.z;
  58636. }
  58637. index = idx + 3;
  58638. }
  58639. };
  58640. //reset copy
  58641. SolidParticleSystem.prototype._resetCopy = function () {
  58642. this._copy.position.x = 0;
  58643. this._copy.position.y = 0;
  58644. this._copy.position.z = 0;
  58645. this._copy.rotation.x = 0;
  58646. this._copy.rotation.y = 0;
  58647. this._copy.rotation.z = 0;
  58648. this._copy.rotationQuaternion = null;
  58649. this._copy.scaling.x = 1.0;
  58650. this._copy.scaling.y = 1.0;
  58651. this._copy.scaling.z = 1.0;
  58652. this._copy.uvs.x = 0;
  58653. this._copy.uvs.y = 0;
  58654. this._copy.uvs.z = 1.0;
  58655. this._copy.uvs.w = 1.0;
  58656. this._copy.color = null;
  58657. this._copy.translateFromPivot = false;
  58658. };
  58659. // _meshBuilder : inserts the shape model in the global SPS mesh
  58660. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58661. var i;
  58662. var u = 0;
  58663. var c = 0;
  58664. var n = 0;
  58665. this._resetCopy();
  58666. if (options && options.positionFunction) { // call to custom positionFunction
  58667. options.positionFunction(this._copy, idx, idxInShape);
  58668. this._mustUnrotateFixedNormals = true;
  58669. }
  58670. if (this._copy.rotationQuaternion) {
  58671. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58672. }
  58673. else {
  58674. this._yaw = this._copy.rotation.y;
  58675. this._pitch = this._copy.rotation.x;
  58676. this._roll = this._copy.rotation.z;
  58677. this._quaternionRotationYPR();
  58678. }
  58679. this._quaternionToRotationMatrix();
  58680. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58681. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58682. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58683. if (this._copy.translateFromPivot) {
  58684. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58685. }
  58686. else {
  58687. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58688. }
  58689. for (i = 0; i < shape.length; i++) {
  58690. this._vertex.x = shape[i].x;
  58691. this._vertex.y = shape[i].y;
  58692. this._vertex.z = shape[i].z;
  58693. if (options && options.vertexFunction) {
  58694. options.vertexFunction(this._copy, this._vertex, i);
  58695. }
  58696. this._vertex.x *= this._copy.scaling.x;
  58697. this._vertex.y *= this._copy.scaling.y;
  58698. this._vertex.z *= this._copy.scaling.z;
  58699. this._vertex.x -= this._scaledPivot.x;
  58700. this._vertex.y -= this._scaledPivot.y;
  58701. this._vertex.z -= this._scaledPivot.z;
  58702. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58703. this._rotated.addInPlace(this._pivotBackTranslation);
  58704. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58705. if (meshUV) {
  58706. 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);
  58707. u += 2;
  58708. }
  58709. if (this._copy.color) {
  58710. this._color = this._copy.color;
  58711. }
  58712. else if (meshCol && meshCol[c] !== undefined) {
  58713. this._color.r = meshCol[c];
  58714. this._color.g = meshCol[c + 1];
  58715. this._color.b = meshCol[c + 2];
  58716. this._color.a = meshCol[c + 3];
  58717. }
  58718. else {
  58719. this._color.r = 1.0;
  58720. this._color.g = 1.0;
  58721. this._color.b = 1.0;
  58722. this._color.a = 1.0;
  58723. }
  58724. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58725. c += 4;
  58726. if (!this.recomputeNormals && meshNor) {
  58727. this._normal.x = meshNor[n];
  58728. this._normal.y = meshNor[n + 1];
  58729. this._normal.z = meshNor[n + 2];
  58730. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58731. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58732. n += 3;
  58733. }
  58734. }
  58735. for (i = 0; i < meshInd.length; i++) {
  58736. var current_ind = p + meshInd[i];
  58737. indices.push(current_ind);
  58738. if (current_ind > 65535) {
  58739. this._needs32Bits = true;
  58740. }
  58741. }
  58742. if (this._pickable) {
  58743. var nbfaces = meshInd.length / 3;
  58744. for (i = 0; i < nbfaces; i++) {
  58745. this.pickedParticles.push({ idx: idx, faceId: i });
  58746. }
  58747. }
  58748. if (this._depthSort) {
  58749. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58750. }
  58751. return this._copy;
  58752. };
  58753. // returns a shape array from positions array
  58754. SolidParticleSystem.prototype._posToShape = function (positions) {
  58755. var shape = [];
  58756. for (var i = 0; i < positions.length; i += 3) {
  58757. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58758. }
  58759. return shape;
  58760. };
  58761. // returns a shapeUV array from a Vector4 uvs
  58762. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58763. var shapeUV = [];
  58764. if (uvs) {
  58765. for (var i = 0; i < uvs.length; i++)
  58766. shapeUV.push(uvs[i]);
  58767. }
  58768. return shapeUV;
  58769. };
  58770. // adds a new particle object in the particles array
  58771. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58772. if (bInfo === void 0) { bInfo = null; }
  58773. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58774. this.particles.push(sp);
  58775. return sp;
  58776. };
  58777. /**
  58778. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58779. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58780. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58781. * @param nb (positive integer) the number of particles to be created from this model
  58782. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58783. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58784. * @returns the number of shapes in the system
  58785. */
  58786. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58787. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58788. var meshInd = mesh.getIndices();
  58789. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58790. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58791. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58792. var bbInfo;
  58793. if (this._particlesIntersect) {
  58794. bbInfo = mesh.getBoundingInfo();
  58795. }
  58796. var shape = this._posToShape(meshPos);
  58797. var shapeUV = this._uvsToShapeUV(meshUV);
  58798. var posfunc = options ? options.positionFunction : null;
  58799. var vtxfunc = options ? options.vertexFunction : null;
  58800. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58801. // particles
  58802. var sp;
  58803. var currentCopy;
  58804. var idx = this.nbParticles;
  58805. for (var i = 0; i < nb; i++) {
  58806. var currentPos = this._positions.length;
  58807. var currentInd = this._indices.length;
  58808. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58809. if (this._updatable) {
  58810. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58811. sp.position.copyFrom(currentCopy.position);
  58812. sp.rotation.copyFrom(currentCopy.rotation);
  58813. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58814. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58815. }
  58816. if (currentCopy.color && sp.color) {
  58817. sp.color.copyFrom(currentCopy.color);
  58818. }
  58819. sp.scaling.copyFrom(currentCopy.scaling);
  58820. sp.uvs.copyFrom(currentCopy.uvs);
  58821. }
  58822. this._index += shape.length;
  58823. idx++;
  58824. }
  58825. this.nbParticles += nb;
  58826. this._shapeCounter++;
  58827. return this._shapeCounter - 1;
  58828. };
  58829. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58830. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58831. this._resetCopy();
  58832. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58833. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58834. }
  58835. if (this._copy.rotationQuaternion) {
  58836. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58837. }
  58838. else {
  58839. this._yaw = this._copy.rotation.y;
  58840. this._pitch = this._copy.rotation.x;
  58841. this._roll = this._copy.rotation.z;
  58842. this._quaternionRotationYPR();
  58843. }
  58844. this._quaternionToRotationMatrix();
  58845. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58846. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58847. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58848. if (this._copy.translateFromPivot) {
  58849. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58850. }
  58851. else {
  58852. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58853. }
  58854. this._shape = particle._model._shape;
  58855. for (var pt = 0; pt < this._shape.length; pt++) {
  58856. this._vertex.x = this._shape[pt].x;
  58857. this._vertex.y = this._shape[pt].y;
  58858. this._vertex.z = this._shape[pt].z;
  58859. if (particle._model._vertexFunction) {
  58860. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58861. }
  58862. this._vertex.x *= this._copy.scaling.x;
  58863. this._vertex.y *= this._copy.scaling.y;
  58864. this._vertex.z *= this._copy.scaling.z;
  58865. this._vertex.x -= this._scaledPivot.x;
  58866. this._vertex.y -= this._scaledPivot.y;
  58867. this._vertex.z -= this._scaledPivot.z;
  58868. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58869. this._rotated.addInPlace(this._pivotBackTranslation);
  58870. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58871. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58872. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58873. }
  58874. particle.position.x = 0.0;
  58875. particle.position.y = 0.0;
  58876. particle.position.z = 0.0;
  58877. particle.rotation.x = 0.0;
  58878. particle.rotation.y = 0.0;
  58879. particle.rotation.z = 0.0;
  58880. particle.rotationQuaternion = null;
  58881. particle.scaling.x = 1.0;
  58882. particle.scaling.y = 1.0;
  58883. particle.scaling.z = 1.0;
  58884. particle.uvs.x = 0.0;
  58885. particle.uvs.y = 0.0;
  58886. particle.uvs.z = 1.0;
  58887. particle.uvs.w = 1.0;
  58888. particle.pivot.x = 0.0;
  58889. particle.pivot.y = 0.0;
  58890. particle.pivot.z = 0.0;
  58891. particle.translateFromPivot = false;
  58892. particle.parentId = null;
  58893. };
  58894. /**
  58895. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58896. * @returns the SPS.
  58897. */
  58898. SolidParticleSystem.prototype.rebuildMesh = function () {
  58899. for (var p = 0; p < this.particles.length; p++) {
  58900. this._rebuildParticle(this.particles[p]);
  58901. }
  58902. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58903. return this;
  58904. };
  58905. /**
  58906. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58907. * This method calls `updateParticle()` for each particle of the SPS.
  58908. * For an animated SPS, it is usually called within the render loop.
  58909. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58910. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58911. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58912. * @returns the SPS.
  58913. */
  58914. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58915. if (start === void 0) { start = 0; }
  58916. if (end === void 0) { end = this.nbParticles - 1; }
  58917. if (update === void 0) { update = true; }
  58918. if (!this._updatable) {
  58919. return this;
  58920. }
  58921. // custom beforeUpdate
  58922. this.beforeUpdateParticles(start, end, update);
  58923. this._cam_axisX.x = 1.0;
  58924. this._cam_axisX.y = 0.0;
  58925. this._cam_axisX.z = 0.0;
  58926. this._cam_axisY.x = 0.0;
  58927. this._cam_axisY.y = 1.0;
  58928. this._cam_axisY.z = 0.0;
  58929. this._cam_axisZ.x = 0.0;
  58930. this._cam_axisZ.y = 0.0;
  58931. this._cam_axisZ.z = 1.0;
  58932. // cases when the World Matrix is to be computed first
  58933. if (this.billboard || this._depthSort) {
  58934. this.mesh.computeWorldMatrix(true);
  58935. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58936. }
  58937. // if the particles will always face the camera
  58938. if (this.billboard) {
  58939. // compute the camera position and un-rotate it by the current mesh rotation
  58940. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58941. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58942. this._cam_axisZ.normalize();
  58943. // same for camera up vector extracted from the cam view matrix
  58944. var view = this._camera.getViewMatrix(true);
  58945. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58946. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58947. this._cam_axisY.normalize();
  58948. this._cam_axisX.normalize();
  58949. }
  58950. // if depthSort, compute the camera global position in the mesh local system
  58951. if (this._depthSort) {
  58952. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58953. }
  58954. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58955. var idx = 0; // current position index in the global array positions32
  58956. var index = 0; // position start index in the global array positions32 of the current particle
  58957. var colidx = 0; // current color index in the global array colors32
  58958. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58959. var uvidx = 0; // current uv index in the global array uvs32
  58960. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58961. var pt = 0; // current index in the particle model shape
  58962. if (this.mesh.isFacetDataEnabled) {
  58963. this._computeBoundingBox = true;
  58964. }
  58965. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58966. if (this._computeBoundingBox) {
  58967. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58968. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58969. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58970. }
  58971. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58972. if (this.mesh._boundingInfo) {
  58973. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58974. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58975. }
  58976. }
  58977. }
  58978. // particle loop
  58979. index = this.particles[start]._pos;
  58980. var vpos = (index / 3) | 0;
  58981. colorIndex = vpos * 4;
  58982. uvIndex = vpos * 2;
  58983. for (var p = start; p <= end; p++) {
  58984. this._particle = this.particles[p];
  58985. this._shape = this._particle._model._shape;
  58986. this._shapeUV = this._particle._model._shapeUV;
  58987. // call to custom user function to update the particle properties
  58988. this.updateParticle(this._particle);
  58989. // camera-particle distance for depth sorting
  58990. if (this._depthSort && this._depthSortParticles) {
  58991. var dsp = this.depthSortedParticles[p];
  58992. dsp.ind = this._particle._ind;
  58993. dsp.indicesLength = this._particle._model._indicesLength;
  58994. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58995. }
  58996. // skip the computations for inactive or already invisible particles
  58997. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58998. // increment indexes for the next particle
  58999. pt = this._shape.length;
  59000. index += pt * 3;
  59001. colorIndex += pt * 4;
  59002. uvIndex += pt * 2;
  59003. continue;
  59004. }
  59005. if (this._particle.isVisible) {
  59006. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59007. this._particleHasParent = (this._particle.parentId !== null);
  59008. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59009. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59010. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59011. // particle rotation matrix
  59012. if (this.billboard) {
  59013. this._particle.rotation.x = 0.0;
  59014. this._particle.rotation.y = 0.0;
  59015. }
  59016. if (this._computeParticleRotation || this.billboard) {
  59017. if (this._particle.rotationQuaternion) {
  59018. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59019. }
  59020. else {
  59021. this._yaw = this._particle.rotation.y;
  59022. this._pitch = this._particle.rotation.x;
  59023. this._roll = this._particle.rotation.z;
  59024. this._quaternionRotationYPR();
  59025. }
  59026. this._quaternionToRotationMatrix();
  59027. }
  59028. if (this._particleHasParent) {
  59029. this._parent = this.particles[this._particle.parentId];
  59030. 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];
  59031. 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];
  59032. 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];
  59033. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59034. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59035. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59036. if (this._computeParticleRotation || this.billboard) {
  59037. 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];
  59038. 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];
  59039. 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];
  59040. 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];
  59041. 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];
  59042. 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];
  59043. 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];
  59044. 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];
  59045. 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];
  59046. }
  59047. }
  59048. else {
  59049. this._particle._globalPosition.x = this._particle.position.x;
  59050. this._particle._globalPosition.y = this._particle.position.y;
  59051. this._particle._globalPosition.z = this._particle.position.z;
  59052. if (this._computeParticleRotation || this.billboard) {
  59053. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59054. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59055. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59056. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59057. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59058. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59059. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59060. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59061. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59062. }
  59063. }
  59064. if (this._particle.translateFromPivot) {
  59065. this._pivotBackTranslation.x = 0.0;
  59066. this._pivotBackTranslation.y = 0.0;
  59067. this._pivotBackTranslation.z = 0.0;
  59068. }
  59069. else {
  59070. this._pivotBackTranslation.x = this._scaledPivot.x;
  59071. this._pivotBackTranslation.y = this._scaledPivot.y;
  59072. this._pivotBackTranslation.z = this._scaledPivot.z;
  59073. }
  59074. // particle vertex loop
  59075. for (pt = 0; pt < this._shape.length; pt++) {
  59076. idx = index + pt * 3;
  59077. colidx = colorIndex + pt * 4;
  59078. uvidx = uvIndex + pt * 2;
  59079. this._vertex.x = this._shape[pt].x;
  59080. this._vertex.y = this._shape[pt].y;
  59081. this._vertex.z = this._shape[pt].z;
  59082. if (this._computeParticleVertex) {
  59083. this.updateParticleVertex(this._particle, this._vertex, pt);
  59084. }
  59085. // positions
  59086. this._vertex.x *= this._particle.scaling.x;
  59087. this._vertex.y *= this._particle.scaling.y;
  59088. this._vertex.z *= this._particle.scaling.z;
  59089. this._vertex.x -= this._scaledPivot.x;
  59090. this._vertex.y -= this._scaledPivot.y;
  59091. this._vertex.z -= this._scaledPivot.z;
  59092. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59093. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59094. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59095. this._rotated.x += this._pivotBackTranslation.x;
  59096. this._rotated.y += this._pivotBackTranslation.y;
  59097. this._rotated.z += this._pivotBackTranslation.z;
  59098. 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;
  59099. 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;
  59100. 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;
  59101. if (this._computeBoundingBox) {
  59102. if (this._positions32[idx] < this._minimum.x) {
  59103. this._minimum.x = this._positions32[idx];
  59104. }
  59105. if (this._positions32[idx] > this._maximum.x) {
  59106. this._maximum.x = this._positions32[idx];
  59107. }
  59108. if (this._positions32[idx + 1] < this._minimum.y) {
  59109. this._minimum.y = this._positions32[idx + 1];
  59110. }
  59111. if (this._positions32[idx + 1] > this._maximum.y) {
  59112. this._maximum.y = this._positions32[idx + 1];
  59113. }
  59114. if (this._positions32[idx + 2] < this._minimum.z) {
  59115. this._minimum.z = this._positions32[idx + 2];
  59116. }
  59117. if (this._positions32[idx + 2] > this._maximum.z) {
  59118. this._maximum.z = this._positions32[idx + 2];
  59119. }
  59120. }
  59121. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59122. if (!this._computeParticleVertex) {
  59123. this._normal.x = this._fixedNormal32[idx];
  59124. this._normal.y = this._fixedNormal32[idx + 1];
  59125. this._normal.z = this._fixedNormal32[idx + 2];
  59126. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59127. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59128. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59129. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59130. 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;
  59131. 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;
  59132. }
  59133. if (this._computeParticleColor && this._particle.color) {
  59134. this._colors32[colidx] = this._particle.color.r;
  59135. this._colors32[colidx + 1] = this._particle.color.g;
  59136. this._colors32[colidx + 2] = this._particle.color.b;
  59137. this._colors32[colidx + 3] = this._particle.color.a;
  59138. }
  59139. if (this._computeParticleTexture) {
  59140. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59141. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59142. }
  59143. }
  59144. }
  59145. // particle just set invisible : scaled to zero and positioned at the origin
  59146. else {
  59147. this._particle._stillInvisible = true; // mark the particle as invisible
  59148. for (pt = 0; pt < this._shape.length; pt++) {
  59149. idx = index + pt * 3;
  59150. colidx = colorIndex + pt * 4;
  59151. uvidx = uvIndex + pt * 2;
  59152. this._positions32[idx] = 0.0;
  59153. this._positions32[idx + 1] = 0.0;
  59154. this._positions32[idx + 2] = 0.0;
  59155. this._normals32[idx] = 0.0;
  59156. this._normals32[idx + 1] = 0.0;
  59157. this._normals32[idx + 2] = 0.0;
  59158. if (this._computeParticleColor && this._particle.color) {
  59159. this._colors32[colidx] = this._particle.color.r;
  59160. this._colors32[colidx + 1] = this._particle.color.g;
  59161. this._colors32[colidx + 2] = this._particle.color.b;
  59162. this._colors32[colidx + 3] = this._particle.color.a;
  59163. }
  59164. if (this._computeParticleTexture) {
  59165. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59166. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59167. }
  59168. }
  59169. }
  59170. // if the particle intersections must be computed : update the bbInfo
  59171. if (this._particlesIntersect) {
  59172. var bInfo = this._particle._boundingInfo;
  59173. var bBox = bInfo.boundingBox;
  59174. var bSphere = bInfo.boundingSphere;
  59175. if (!this._bSphereOnly) {
  59176. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59177. for (var b = 0; b < bBox.vectors.length; b++) {
  59178. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59179. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59180. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59181. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59182. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59183. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59184. 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;
  59185. 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;
  59186. 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;
  59187. }
  59188. bBox._update(this.mesh._worldMatrix);
  59189. }
  59190. // place and scale the particle bouding sphere in the SPS local system, then update it
  59191. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59192. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59193. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59194. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59195. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59196. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59197. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59198. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59199. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59200. 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));
  59201. bSphere._update(this.mesh._worldMatrix);
  59202. }
  59203. // increment indexes for the next particle
  59204. index = idx + 3;
  59205. colorIndex = colidx + 4;
  59206. uvIndex = uvidx + 2;
  59207. }
  59208. // if the VBO must be updated
  59209. if (update) {
  59210. if (this._computeParticleColor) {
  59211. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59212. }
  59213. if (this._computeParticleTexture) {
  59214. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59215. }
  59216. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59217. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59218. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59219. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59220. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59221. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59222. for (var i = 0; i < this._normals32.length; i++) {
  59223. this._fixedNormal32[i] = this._normals32[i];
  59224. }
  59225. }
  59226. if (!this.mesh.areNormalsFrozen) {
  59227. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59228. }
  59229. }
  59230. if (this._depthSort && this._depthSortParticles) {
  59231. this.depthSortedParticles.sort(this._depthSortFunction);
  59232. var dspl = this.depthSortedParticles.length;
  59233. var sorted = 0;
  59234. var lind = 0;
  59235. var sind = 0;
  59236. var sid = 0;
  59237. for (sorted = 0; sorted < dspl; sorted++) {
  59238. lind = this.depthSortedParticles[sorted].indicesLength;
  59239. sind = this.depthSortedParticles[sorted].ind;
  59240. for (var i = 0; i < lind; i++) {
  59241. this._indices32[sid] = this._indices[sind + i];
  59242. sid++;
  59243. }
  59244. }
  59245. this.mesh.updateIndices(this._indices32);
  59246. }
  59247. }
  59248. if (this._computeBoundingBox) {
  59249. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59250. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59251. }
  59252. this.afterUpdateParticles(start, end, update);
  59253. return this;
  59254. };
  59255. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59256. this._halfroll = this._roll * 0.5;
  59257. this._halfpitch = this._pitch * 0.5;
  59258. this._halfyaw = this._yaw * 0.5;
  59259. this._sinRoll = Math.sin(this._halfroll);
  59260. this._cosRoll = Math.cos(this._halfroll);
  59261. this._sinPitch = Math.sin(this._halfpitch);
  59262. this._cosPitch = Math.cos(this._halfpitch);
  59263. this._sinYaw = Math.sin(this._halfyaw);
  59264. this._cosYaw = Math.cos(this._halfyaw);
  59265. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59266. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59267. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59268. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59269. };
  59270. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59271. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59272. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59273. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59274. this._rotMatrix.m[3] = 0;
  59275. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59276. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59277. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59278. this._rotMatrix.m[7] = 0;
  59279. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59280. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59281. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59282. this._rotMatrix.m[11] = 0;
  59283. this._rotMatrix.m[12] = 0;
  59284. this._rotMatrix.m[13] = 0;
  59285. this._rotMatrix.m[14] = 0;
  59286. this._rotMatrix.m[15] = 1.0;
  59287. };
  59288. /**
  59289. * Disposes the SPS.
  59290. */
  59291. SolidParticleSystem.prototype.dispose = function () {
  59292. this.mesh.dispose();
  59293. this.vars = null;
  59294. // drop references to internal big arrays for the GC
  59295. this._positions = null;
  59296. this._indices = null;
  59297. this._normals = null;
  59298. this._uvs = null;
  59299. this._colors = null;
  59300. this._indices32 = null;
  59301. this._positions32 = null;
  59302. this._normals32 = null;
  59303. this._fixedNormal32 = null;
  59304. this._uvs32 = null;
  59305. this._colors32 = null;
  59306. this.pickedParticles = null;
  59307. };
  59308. /**
  59309. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59310. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59311. * @returns the SPS.
  59312. */
  59313. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59314. if (!this._isVisibilityBoxLocked) {
  59315. this.mesh.refreshBoundingInfo();
  59316. }
  59317. return this;
  59318. };
  59319. /**
  59320. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59321. * @param size the size (float) of the visibility box
  59322. * note : this doesn't lock the SPS mesh bounding box.
  59323. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59324. */
  59325. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59326. var vis = size / 2;
  59327. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59328. };
  59329. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59330. /**
  59331. * Gets whether the SPS as always visible or not
  59332. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59333. */
  59334. get: function () {
  59335. return this._alwaysVisible;
  59336. },
  59337. /**
  59338. * Sets the SPS as always visible or not
  59339. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59340. */
  59341. set: function (val) {
  59342. this._alwaysVisible = val;
  59343. this.mesh.alwaysSelectAsActiveMesh = val;
  59344. },
  59345. enumerable: true,
  59346. configurable: true
  59347. });
  59348. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59349. /**
  59350. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59351. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59352. */
  59353. get: function () {
  59354. return this._isVisibilityBoxLocked;
  59355. },
  59356. /**
  59357. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59358. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59359. */
  59360. set: function (val) {
  59361. this._isVisibilityBoxLocked = val;
  59362. var boundingInfo = this.mesh.getBoundingInfo();
  59363. boundingInfo.isLocked = val;
  59364. },
  59365. enumerable: true,
  59366. configurable: true
  59367. });
  59368. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59369. /**
  59370. * Gets if `setParticles()` computes the particle rotations or not.
  59371. * Default value : true. The SPS is faster when it's set to false.
  59372. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59373. */
  59374. get: function () {
  59375. return this._computeParticleRotation;
  59376. },
  59377. /**
  59378. * Tells to `setParticles()` to compute the particle rotations or not.
  59379. * Default value : true. The SPS is faster when it's set to false.
  59380. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59381. */
  59382. set: function (val) {
  59383. this._computeParticleRotation = val;
  59384. },
  59385. enumerable: true,
  59386. configurable: true
  59387. });
  59388. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59389. /**
  59390. * Gets if `setParticles()` computes the particle colors or not.
  59391. * Default value : true. The SPS is faster when it's set to false.
  59392. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59393. */
  59394. get: function () {
  59395. return this._computeParticleColor;
  59396. },
  59397. /**
  59398. * Tells to `setParticles()` to compute the particle colors or not.
  59399. * Default value : true. The SPS is faster when it's set to false.
  59400. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59401. */
  59402. set: function (val) {
  59403. this._computeParticleColor = val;
  59404. },
  59405. enumerable: true,
  59406. configurable: true
  59407. });
  59408. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59409. /**
  59410. * Gets if `setParticles()` computes the particle textures or not.
  59411. * Default value : true. The SPS is faster when it's set to false.
  59412. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59413. */
  59414. get: function () {
  59415. return this._computeParticleTexture;
  59416. },
  59417. set: function (val) {
  59418. this._computeParticleTexture = val;
  59419. },
  59420. enumerable: true,
  59421. configurable: true
  59422. });
  59423. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59424. /**
  59425. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59426. * Default value : false. The SPS is faster when it's set to false.
  59427. * Note : the particle custom vertex positions aren't stored values.
  59428. */
  59429. get: function () {
  59430. return this._computeParticleVertex;
  59431. },
  59432. /**
  59433. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59434. * Default value : false. The SPS is faster when it's set to false.
  59435. * Note : the particle custom vertex positions aren't stored values.
  59436. */
  59437. set: function (val) {
  59438. this._computeParticleVertex = val;
  59439. },
  59440. enumerable: true,
  59441. configurable: true
  59442. });
  59443. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59444. /**
  59445. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59446. */
  59447. get: function () {
  59448. return this._computeBoundingBox;
  59449. },
  59450. /**
  59451. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59452. */
  59453. set: function (val) {
  59454. this._computeBoundingBox = val;
  59455. },
  59456. enumerable: true,
  59457. configurable: true
  59458. });
  59459. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59460. /**
  59461. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59462. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59463. * Default : `true`
  59464. */
  59465. get: function () {
  59466. return this._depthSortParticles;
  59467. },
  59468. /**
  59469. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59470. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59471. * Default : `true`
  59472. */
  59473. set: function (val) {
  59474. this._depthSortParticles = val;
  59475. },
  59476. enumerable: true,
  59477. configurable: true
  59478. });
  59479. // =======================================================================
  59480. // Particle behavior logic
  59481. // these following methods may be overwritten by the user to fit his needs
  59482. /**
  59483. * This function does nothing. It may be overwritten to set all the particle first values.
  59484. * The SPS doesn't call this function, you may have to call it by your own.
  59485. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59486. */
  59487. SolidParticleSystem.prototype.initParticles = function () {
  59488. };
  59489. /**
  59490. * This function does nothing. It may be overwritten to recycle a particle.
  59491. * The SPS doesn't call this function, you may have to call it by your own.
  59492. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59493. * @param particle The particle to recycle
  59494. * @returns the recycled particle
  59495. */
  59496. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59497. return particle;
  59498. };
  59499. /**
  59500. * Updates a particle : this function should be overwritten by the user.
  59501. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59502. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59503. * @example : just set a particle position or velocity and recycle conditions
  59504. * @param particle The particle to update
  59505. * @returns the updated particle
  59506. */
  59507. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59508. return particle;
  59509. };
  59510. /**
  59511. * Updates a vertex of a particle : it can be overwritten by the user.
  59512. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59513. * @param particle the current particle
  59514. * @param vertex the current index of the current particle
  59515. * @param pt the index of the current vertex in the particle shape
  59516. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59517. * @example : just set a vertex particle position
  59518. * @returns the updated vertex
  59519. */
  59520. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59521. return vertex;
  59522. };
  59523. /**
  59524. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59525. * This does nothing and may be overwritten by the user.
  59526. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59527. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59528. * @param update the boolean update value actually passed to setParticles()
  59529. */
  59530. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59531. };
  59532. /**
  59533. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59534. * This will be passed three parameters.
  59535. * This does nothing and may be overwritten by the user.
  59536. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59537. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59538. * @param update the boolean update value actually passed to setParticles()
  59539. */
  59540. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59541. };
  59542. return SolidParticleSystem;
  59543. }());
  59544. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59545. })(BABYLON || (BABYLON = {}));
  59546. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59547. var BABYLON;
  59548. (function (BABYLON) {
  59549. var ShaderMaterial = /** @class */ (function (_super) {
  59550. __extends(ShaderMaterial, _super);
  59551. function ShaderMaterial(name, scene, shaderPath, options) {
  59552. var _this = _super.call(this, name, scene) || this;
  59553. _this._textures = {};
  59554. _this._textureArrays = {};
  59555. _this._floats = {};
  59556. _this._ints = {};
  59557. _this._floatsArrays = {};
  59558. _this._colors3 = {};
  59559. _this._colors3Arrays = {};
  59560. _this._colors4 = {};
  59561. _this._vectors2 = {};
  59562. _this._vectors3 = {};
  59563. _this._vectors4 = {};
  59564. _this._matrices = {};
  59565. _this._matrices3x3 = {};
  59566. _this._matrices2x2 = {};
  59567. _this._vectors2Arrays = {};
  59568. _this._vectors3Arrays = {};
  59569. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59570. _this._shaderPath = shaderPath;
  59571. options.needAlphaBlending = options.needAlphaBlending || false;
  59572. options.needAlphaTesting = options.needAlphaTesting || false;
  59573. options.attributes = options.attributes || ["position", "normal", "uv"];
  59574. options.uniforms = options.uniforms || ["worldViewProjection"];
  59575. options.uniformBuffers = options.uniformBuffers || [];
  59576. options.samplers = options.samplers || [];
  59577. options.defines = options.defines || [];
  59578. _this._options = options;
  59579. return _this;
  59580. }
  59581. ShaderMaterial.prototype.getClassName = function () {
  59582. return "ShaderMaterial";
  59583. };
  59584. ShaderMaterial.prototype.needAlphaBlending = function () {
  59585. return this._options.needAlphaBlending;
  59586. };
  59587. ShaderMaterial.prototype.needAlphaTesting = function () {
  59588. return this._options.needAlphaTesting;
  59589. };
  59590. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59591. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59592. this._options.uniforms.push(uniformName);
  59593. }
  59594. };
  59595. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59596. if (this._options.samplers.indexOf(name) === -1) {
  59597. this._options.samplers.push(name);
  59598. }
  59599. this._textures[name] = texture;
  59600. return this;
  59601. };
  59602. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59603. if (this._options.samplers.indexOf(name) === -1) {
  59604. this._options.samplers.push(name);
  59605. }
  59606. this._checkUniform(name);
  59607. this._textureArrays[name] = textures;
  59608. return this;
  59609. };
  59610. ShaderMaterial.prototype.setFloat = function (name, value) {
  59611. this._checkUniform(name);
  59612. this._floats[name] = value;
  59613. return this;
  59614. };
  59615. ShaderMaterial.prototype.setInt = function (name, value) {
  59616. this._checkUniform(name);
  59617. this._ints[name] = value;
  59618. return this;
  59619. };
  59620. ShaderMaterial.prototype.setFloats = function (name, value) {
  59621. this._checkUniform(name);
  59622. this._floatsArrays[name] = value;
  59623. return this;
  59624. };
  59625. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59626. this._checkUniform(name);
  59627. this._colors3[name] = value;
  59628. return this;
  59629. };
  59630. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59631. this._checkUniform(name);
  59632. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59633. color.toArray(arr, arr.length);
  59634. return arr;
  59635. }, []);
  59636. return this;
  59637. };
  59638. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59639. this._checkUniform(name);
  59640. this._colors4[name] = value;
  59641. return this;
  59642. };
  59643. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59644. this._checkUniform(name);
  59645. this._vectors2[name] = value;
  59646. return this;
  59647. };
  59648. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59649. this._checkUniform(name);
  59650. this._vectors3[name] = value;
  59651. return this;
  59652. };
  59653. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59654. this._checkUniform(name);
  59655. this._vectors4[name] = value;
  59656. return this;
  59657. };
  59658. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59659. this._checkUniform(name);
  59660. this._matrices[name] = value;
  59661. return this;
  59662. };
  59663. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59664. this._checkUniform(name);
  59665. this._matrices3x3[name] = value;
  59666. return this;
  59667. };
  59668. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59669. this._checkUniform(name);
  59670. this._matrices2x2[name] = value;
  59671. return this;
  59672. };
  59673. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59674. this._checkUniform(name);
  59675. this._vectors2Arrays[name] = value;
  59676. return this;
  59677. };
  59678. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59679. this._checkUniform(name);
  59680. this._vectors3Arrays[name] = value;
  59681. return this;
  59682. };
  59683. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59684. if (!mesh) {
  59685. return true;
  59686. }
  59687. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59688. return false;
  59689. }
  59690. return false;
  59691. };
  59692. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59693. var scene = this.getScene();
  59694. var engine = scene.getEngine();
  59695. if (!this.checkReadyOnEveryCall) {
  59696. if (this._renderId === scene.getRenderId()) {
  59697. if (this._checkCache(scene, mesh, useInstances)) {
  59698. return true;
  59699. }
  59700. }
  59701. }
  59702. // Instances
  59703. var defines = [];
  59704. var attribs = [];
  59705. var fallbacks = new BABYLON.EffectFallbacks();
  59706. if (useInstances) {
  59707. defines.push("#define INSTANCES");
  59708. }
  59709. for (var index = 0; index < this._options.defines.length; index++) {
  59710. defines.push(this._options.defines[index]);
  59711. }
  59712. for (var index = 0; index < this._options.attributes.length; index++) {
  59713. attribs.push(this._options.attributes[index]);
  59714. }
  59715. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59716. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59717. defines.push("#define VERTEXCOLOR");
  59718. }
  59719. // Bones
  59720. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59721. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59722. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59723. if (mesh.numBoneInfluencers > 4) {
  59724. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59725. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59726. }
  59727. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59728. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59729. fallbacks.addCPUSkinningFallback(0, mesh);
  59730. if (this._options.uniforms.indexOf("mBones") === -1) {
  59731. this._options.uniforms.push("mBones");
  59732. }
  59733. }
  59734. else {
  59735. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59736. }
  59737. // Textures
  59738. for (var name in this._textures) {
  59739. if (!this._textures[name].isReady()) {
  59740. return false;
  59741. }
  59742. }
  59743. // Alpha test
  59744. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59745. defines.push("#define ALPHATEST");
  59746. }
  59747. var previousEffect = this._effect;
  59748. var join = defines.join("\n");
  59749. this._effect = engine.createEffect(this._shaderPath, {
  59750. attributes: attribs,
  59751. uniformsNames: this._options.uniforms,
  59752. uniformBuffersNames: this._options.uniformBuffers,
  59753. samplers: this._options.samplers,
  59754. defines: join,
  59755. fallbacks: fallbacks,
  59756. onCompiled: this.onCompiled,
  59757. onError: this.onError
  59758. }, engine);
  59759. if (!this._effect.isReady()) {
  59760. return false;
  59761. }
  59762. if (previousEffect !== this._effect) {
  59763. scene.resetCachedMaterial();
  59764. }
  59765. this._renderId = scene.getRenderId();
  59766. return true;
  59767. };
  59768. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59769. var scene = this.getScene();
  59770. if (!this._effect) {
  59771. return;
  59772. }
  59773. if (this._options.uniforms.indexOf("world") !== -1) {
  59774. this._effect.setMatrix("world", world);
  59775. }
  59776. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59777. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59778. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59779. }
  59780. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59781. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59782. }
  59783. };
  59784. ShaderMaterial.prototype.bind = function (world, mesh) {
  59785. // Std values
  59786. this.bindOnlyWorldMatrix(world);
  59787. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59788. if (this._options.uniforms.indexOf("view") !== -1) {
  59789. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59790. }
  59791. if (this._options.uniforms.indexOf("projection") !== -1) {
  59792. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59793. }
  59794. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59795. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59796. }
  59797. // Bones
  59798. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59799. var name;
  59800. // Texture
  59801. for (name in this._textures) {
  59802. this._effect.setTexture(name, this._textures[name]);
  59803. }
  59804. // Texture arrays
  59805. for (name in this._textureArrays) {
  59806. this._effect.setTextureArray(name, this._textureArrays[name]);
  59807. }
  59808. // Int
  59809. for (name in this._ints) {
  59810. this._effect.setInt(name, this._ints[name]);
  59811. }
  59812. // Float
  59813. for (name in this._floats) {
  59814. this._effect.setFloat(name, this._floats[name]);
  59815. }
  59816. // Floats
  59817. for (name in this._floatsArrays) {
  59818. this._effect.setArray(name, this._floatsArrays[name]);
  59819. }
  59820. // Color3
  59821. for (name in this._colors3) {
  59822. this._effect.setColor3(name, this._colors3[name]);
  59823. }
  59824. for (name in this._colors3Arrays) {
  59825. this._effect.setArray3(name, this._colors3Arrays[name]);
  59826. }
  59827. // Color4
  59828. for (name in this._colors4) {
  59829. var color = this._colors4[name];
  59830. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59831. }
  59832. // Vector2
  59833. for (name in this._vectors2) {
  59834. this._effect.setVector2(name, this._vectors2[name]);
  59835. }
  59836. // Vector3
  59837. for (name in this._vectors3) {
  59838. this._effect.setVector3(name, this._vectors3[name]);
  59839. }
  59840. // Vector4
  59841. for (name in this._vectors4) {
  59842. this._effect.setVector4(name, this._vectors4[name]);
  59843. }
  59844. // Matrix
  59845. for (name in this._matrices) {
  59846. this._effect.setMatrix(name, this._matrices[name]);
  59847. }
  59848. // Matrix 3x3
  59849. for (name in this._matrices3x3) {
  59850. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59851. }
  59852. // Matrix 2x2
  59853. for (name in this._matrices2x2) {
  59854. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59855. }
  59856. // Vector2Array
  59857. for (name in this._vectors2Arrays) {
  59858. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59859. }
  59860. // Vector3Array
  59861. for (name in this._vectors3Arrays) {
  59862. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59863. }
  59864. }
  59865. this._afterBind(mesh);
  59866. };
  59867. ShaderMaterial.prototype.getActiveTextures = function () {
  59868. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59869. for (var name in this._textures) {
  59870. activeTextures.push(this._textures[name]);
  59871. }
  59872. for (var name in this._textureArrays) {
  59873. var array = this._textureArrays[name];
  59874. for (var index = 0; index < array.length; index++) {
  59875. activeTextures.push(array[index]);
  59876. }
  59877. }
  59878. return activeTextures;
  59879. };
  59880. ShaderMaterial.prototype.hasTexture = function (texture) {
  59881. if (_super.prototype.hasTexture.call(this, texture)) {
  59882. return true;
  59883. }
  59884. for (var name in this._textures) {
  59885. if (this._textures[name] === texture) {
  59886. return true;
  59887. }
  59888. }
  59889. for (var name in this._textureArrays) {
  59890. var array = this._textureArrays[name];
  59891. for (var index = 0; index < array.length; index++) {
  59892. if (array[index] === texture) {
  59893. return true;
  59894. }
  59895. }
  59896. }
  59897. return false;
  59898. };
  59899. ShaderMaterial.prototype.clone = function (name) {
  59900. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59901. return newShaderMaterial;
  59902. };
  59903. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59904. if (forceDisposeTextures) {
  59905. var name;
  59906. for (name in this._textures) {
  59907. this._textures[name].dispose();
  59908. }
  59909. for (name in this._textureArrays) {
  59910. var array = this._textureArrays[name];
  59911. for (var index = 0; index < array.length; index++) {
  59912. array[index].dispose();
  59913. }
  59914. }
  59915. }
  59916. this._textures = {};
  59917. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59918. };
  59919. ShaderMaterial.prototype.serialize = function () {
  59920. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59921. serializationObject.customType = "BABYLON.ShaderMaterial";
  59922. serializationObject.options = this._options;
  59923. serializationObject.shaderPath = this._shaderPath;
  59924. var name;
  59925. // Texture
  59926. serializationObject.textures = {};
  59927. for (name in this._textures) {
  59928. serializationObject.textures[name] = this._textures[name].serialize();
  59929. }
  59930. // Texture arrays
  59931. serializationObject.textureArrays = {};
  59932. for (name in this._textureArrays) {
  59933. serializationObject.textureArrays[name] = [];
  59934. var array = this._textureArrays[name];
  59935. for (var index = 0; index < array.length; index++) {
  59936. serializationObject.textureArrays[name].push(array[index].serialize());
  59937. }
  59938. }
  59939. // Float
  59940. serializationObject.floats = {};
  59941. for (name in this._floats) {
  59942. serializationObject.floats[name] = this._floats[name];
  59943. }
  59944. // Float s
  59945. serializationObject.FloatArrays = {};
  59946. for (name in this._floatsArrays) {
  59947. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59948. }
  59949. // Color3
  59950. serializationObject.colors3 = {};
  59951. for (name in this._colors3) {
  59952. serializationObject.colors3[name] = this._colors3[name].asArray();
  59953. }
  59954. // Color3 array
  59955. serializationObject.colors3Arrays = {};
  59956. for (name in this._colors3Arrays) {
  59957. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59958. }
  59959. // Color4
  59960. serializationObject.colors4 = {};
  59961. for (name in this._colors4) {
  59962. serializationObject.colors4[name] = this._colors4[name].asArray();
  59963. }
  59964. // Vector2
  59965. serializationObject.vectors2 = {};
  59966. for (name in this._vectors2) {
  59967. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59968. }
  59969. // Vector3
  59970. serializationObject.vectors3 = {};
  59971. for (name in this._vectors3) {
  59972. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59973. }
  59974. // Vector4
  59975. serializationObject.vectors4 = {};
  59976. for (name in this._vectors4) {
  59977. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59978. }
  59979. // Matrix
  59980. serializationObject.matrices = {};
  59981. for (name in this._matrices) {
  59982. serializationObject.matrices[name] = this._matrices[name].asArray();
  59983. }
  59984. // Matrix 3x3
  59985. serializationObject.matrices3x3 = {};
  59986. for (name in this._matrices3x3) {
  59987. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59988. }
  59989. // Matrix 2x2
  59990. serializationObject.matrices2x2 = {};
  59991. for (name in this._matrices2x2) {
  59992. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59993. }
  59994. // Vector2Array
  59995. serializationObject.vectors2Arrays = {};
  59996. for (name in this._vectors2Arrays) {
  59997. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59998. }
  59999. // Vector3Array
  60000. serializationObject.vectors3Arrays = {};
  60001. for (name in this._vectors3Arrays) {
  60002. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60003. }
  60004. return serializationObject;
  60005. };
  60006. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60007. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60008. var name;
  60009. // Texture
  60010. for (name in source.textures) {
  60011. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60012. }
  60013. // Texture arrays
  60014. for (name in source.textureArrays) {
  60015. var array = source.textureArrays[name];
  60016. var textureArray = new Array();
  60017. for (var index = 0; index < array.length; index++) {
  60018. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60019. }
  60020. material.setTextureArray(name, textureArray);
  60021. }
  60022. // Float
  60023. for (name in source.floats) {
  60024. material.setFloat(name, source.floats[name]);
  60025. }
  60026. // Float s
  60027. for (name in source.floatsArrays) {
  60028. material.setFloats(name, source.floatsArrays[name]);
  60029. }
  60030. // Color3
  60031. for (name in source.colors3) {
  60032. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60033. }
  60034. // Color3 arrays
  60035. for (name in source.colors3Arrays) {
  60036. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60037. if (i % 3 === 0) {
  60038. arr.push([num]);
  60039. }
  60040. else {
  60041. arr[arr.length - 1].push(num);
  60042. }
  60043. return arr;
  60044. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60045. material.setColor3Array(name, colors);
  60046. }
  60047. // Color4
  60048. for (name in source.colors4) {
  60049. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60050. }
  60051. // Vector2
  60052. for (name in source.vectors2) {
  60053. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60054. }
  60055. // Vector3
  60056. for (name in source.vectors3) {
  60057. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60058. }
  60059. // Vector4
  60060. for (name in source.vectors4) {
  60061. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60062. }
  60063. // Matrix
  60064. for (name in source.matrices) {
  60065. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60066. }
  60067. // Matrix 3x3
  60068. for (name in source.matrices3x3) {
  60069. material.setMatrix3x3(name, source.matrices3x3[name]);
  60070. }
  60071. // Matrix 2x2
  60072. for (name in source.matrices2x2) {
  60073. material.setMatrix2x2(name, source.matrices2x2[name]);
  60074. }
  60075. // Vector2Array
  60076. for (name in source.vectors2Arrays) {
  60077. material.setArray2(name, source.vectors2Arrays[name]);
  60078. }
  60079. // Vector3Array
  60080. for (name in source.vectors3Arrays) {
  60081. material.setArray3(name, source.vectors3Arrays[name]);
  60082. }
  60083. return material;
  60084. };
  60085. return ShaderMaterial;
  60086. }(BABYLON.Material));
  60087. BABYLON.ShaderMaterial = ShaderMaterial;
  60088. })(BABYLON || (BABYLON = {}));
  60089. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60090. var BABYLON;
  60091. (function (BABYLON) {
  60092. var GroundMesh = /** @class */ (function (_super) {
  60093. __extends(GroundMesh, _super);
  60094. function GroundMesh(name, scene) {
  60095. var _this = _super.call(this, name, scene) || this;
  60096. _this.generateOctree = false;
  60097. return _this;
  60098. }
  60099. GroundMesh.prototype.getClassName = function () {
  60100. return "GroundMesh";
  60101. };
  60102. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60103. get: function () {
  60104. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60105. },
  60106. enumerable: true,
  60107. configurable: true
  60108. });
  60109. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60110. get: function () {
  60111. return this._subdivisionsX;
  60112. },
  60113. enumerable: true,
  60114. configurable: true
  60115. });
  60116. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60117. get: function () {
  60118. return this._subdivisionsY;
  60119. },
  60120. enumerable: true,
  60121. configurable: true
  60122. });
  60123. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60124. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60125. this._subdivisionsX = chunksCount;
  60126. this._subdivisionsY = chunksCount;
  60127. this.subdivide(chunksCount);
  60128. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60129. };
  60130. /**
  60131. * Returns a height (y) value in the Worl system :
  60132. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60133. * Returns the ground y position if (x, z) are outside the ground surface.
  60134. */
  60135. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60136. var world = this.getWorldMatrix();
  60137. var invMat = BABYLON.Tmp.Matrix[5];
  60138. world.invertToRef(invMat);
  60139. var tmpVect = BABYLON.Tmp.Vector3[8];
  60140. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60141. x = tmpVect.x;
  60142. z = tmpVect.z;
  60143. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60144. return this.position.y;
  60145. }
  60146. if (!this._heightQuads || this._heightQuads.length == 0) {
  60147. this._initHeightQuads();
  60148. this._computeHeightQuads();
  60149. }
  60150. var facet = this._getFacetAt(x, z);
  60151. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60152. // return y in the World system
  60153. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60154. return tmpVect.y;
  60155. };
  60156. /**
  60157. * Returns a normalized vector (Vector3) orthogonal to the ground
  60158. * at the ground coordinates (x, z) expressed in the World system.
  60159. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60160. */
  60161. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60162. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60163. this.getNormalAtCoordinatesToRef(x, z, normal);
  60164. return normal;
  60165. };
  60166. /**
  60167. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60168. * at the ground coordinates (x, z) expressed in the World system.
  60169. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60170. * Returns the GroundMesh.
  60171. */
  60172. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60173. var world = this.getWorldMatrix();
  60174. var tmpMat = BABYLON.Tmp.Matrix[5];
  60175. world.invertToRef(tmpMat);
  60176. var tmpVect = BABYLON.Tmp.Vector3[8];
  60177. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60178. x = tmpVect.x;
  60179. z = tmpVect.z;
  60180. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60181. return this;
  60182. }
  60183. if (!this._heightQuads || this._heightQuads.length == 0) {
  60184. this._initHeightQuads();
  60185. this._computeHeightQuads();
  60186. }
  60187. var facet = this._getFacetAt(x, z);
  60188. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60189. return this;
  60190. };
  60191. /**
  60192. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60193. * if the ground has been updated.
  60194. * This can be used in the render loop.
  60195. * Returns the GroundMesh.
  60196. */
  60197. GroundMesh.prototype.updateCoordinateHeights = function () {
  60198. if (!this._heightQuads || this._heightQuads.length == 0) {
  60199. this._initHeightQuads();
  60200. }
  60201. this._computeHeightQuads();
  60202. return this;
  60203. };
  60204. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60205. GroundMesh.prototype._getFacetAt = function (x, z) {
  60206. // retrieve col and row from x, z coordinates in the ground local system
  60207. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60208. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60209. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60210. var facet;
  60211. if (z < quad.slope.x * x + quad.slope.y) {
  60212. facet = quad.facet1;
  60213. }
  60214. else {
  60215. facet = quad.facet2;
  60216. }
  60217. return facet;
  60218. };
  60219. // Creates and populates the heightMap array with "facet" elements :
  60220. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60221. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60222. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60223. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60224. // Returns the GroundMesh.
  60225. GroundMesh.prototype._initHeightQuads = function () {
  60226. var subdivisionsX = this._subdivisionsX;
  60227. var subdivisionsY = this._subdivisionsY;
  60228. this._heightQuads = new Array();
  60229. for (var row = 0; row < subdivisionsY; row++) {
  60230. for (var col = 0; col < subdivisionsX; col++) {
  60231. 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) };
  60232. this._heightQuads[row * subdivisionsX + col] = quad;
  60233. }
  60234. }
  60235. return this;
  60236. };
  60237. // Compute each quad element values and update the the heightMap array :
  60238. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60239. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60240. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60241. // Returns the GroundMesh.
  60242. GroundMesh.prototype._computeHeightQuads = function () {
  60243. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60244. if (!positions) {
  60245. return this;
  60246. }
  60247. var v1 = BABYLON.Tmp.Vector3[3];
  60248. var v2 = BABYLON.Tmp.Vector3[2];
  60249. var v3 = BABYLON.Tmp.Vector3[1];
  60250. var v4 = BABYLON.Tmp.Vector3[0];
  60251. var v1v2 = BABYLON.Tmp.Vector3[4];
  60252. var v1v3 = BABYLON.Tmp.Vector3[5];
  60253. var v1v4 = BABYLON.Tmp.Vector3[6];
  60254. var norm1 = BABYLON.Tmp.Vector3[7];
  60255. var norm2 = BABYLON.Tmp.Vector3[8];
  60256. var i = 0;
  60257. var j = 0;
  60258. var k = 0;
  60259. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60260. var h = 0;
  60261. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60262. var d2 = 0;
  60263. var subdivisionsX = this._subdivisionsX;
  60264. var subdivisionsY = this._subdivisionsY;
  60265. for (var row = 0; row < subdivisionsY; row++) {
  60266. for (var col = 0; col < subdivisionsX; col++) {
  60267. i = col * 3;
  60268. j = row * (subdivisionsX + 1) * 3;
  60269. k = (row + 1) * (subdivisionsX + 1) * 3;
  60270. v1.x = positions[j + i];
  60271. v1.y = positions[j + i + 1];
  60272. v1.z = positions[j + i + 2];
  60273. v2.x = positions[j + i + 3];
  60274. v2.y = positions[j + i + 4];
  60275. v2.z = positions[j + i + 5];
  60276. v3.x = positions[k + i];
  60277. v3.y = positions[k + i + 1];
  60278. v3.z = positions[k + i + 2];
  60279. v4.x = positions[k + i + 3];
  60280. v4.y = positions[k + i + 4];
  60281. v4.z = positions[k + i + 5];
  60282. // 2D slope V1V4
  60283. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60284. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60285. // facet equations :
  60286. // we compute each facet normal vector
  60287. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60288. // we compute the value d by applying the equation to v1 which belongs to the plane
  60289. // then we store the facet equation in a Vector4
  60290. v2.subtractToRef(v1, v1v2);
  60291. v3.subtractToRef(v1, v1v3);
  60292. v4.subtractToRef(v1, v1v4);
  60293. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60294. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60295. norm1.normalize();
  60296. norm2.normalize();
  60297. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60298. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60299. var quad = this._heightQuads[row * subdivisionsX + col];
  60300. quad.slope.copyFromFloats(cd, h);
  60301. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60302. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60303. }
  60304. }
  60305. return this;
  60306. };
  60307. GroundMesh.prototype.serialize = function (serializationObject) {
  60308. _super.prototype.serialize.call(this, serializationObject);
  60309. serializationObject.subdivisionsX = this._subdivisionsX;
  60310. serializationObject.subdivisionsY = this._subdivisionsY;
  60311. serializationObject.minX = this._minX;
  60312. serializationObject.maxX = this._maxX;
  60313. serializationObject.minZ = this._minZ;
  60314. serializationObject.maxZ = this._maxZ;
  60315. serializationObject.width = this._width;
  60316. serializationObject.height = this._height;
  60317. };
  60318. GroundMesh.Parse = function (parsedMesh, scene) {
  60319. var result = new GroundMesh(parsedMesh.name, scene);
  60320. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60321. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60322. result._minX = parsedMesh.minX;
  60323. result._maxX = parsedMesh.maxX;
  60324. result._minZ = parsedMesh.minZ;
  60325. result._maxZ = parsedMesh.maxZ;
  60326. result._width = parsedMesh.width;
  60327. result._height = parsedMesh.height;
  60328. return result;
  60329. };
  60330. return GroundMesh;
  60331. }(BABYLON.Mesh));
  60332. BABYLON.GroundMesh = GroundMesh;
  60333. })(BABYLON || (BABYLON = {}));
  60334. //# sourceMappingURL=babylon.groundMesh.js.map
  60335. var BABYLON;
  60336. (function (BABYLON) {
  60337. /**
  60338. * Creates an instance based on a source mesh.
  60339. */
  60340. var InstancedMesh = /** @class */ (function (_super) {
  60341. __extends(InstancedMesh, _super);
  60342. function InstancedMesh(name, source) {
  60343. var _this = _super.call(this, name, source.getScene()) || this;
  60344. source.instances.push(_this);
  60345. _this._sourceMesh = source;
  60346. _this.position.copyFrom(source.position);
  60347. _this.rotation.copyFrom(source.rotation);
  60348. _this.scaling.copyFrom(source.scaling);
  60349. if (source.rotationQuaternion) {
  60350. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60351. }
  60352. _this.infiniteDistance = source.infiniteDistance;
  60353. _this.setPivotMatrix(source.getPivotMatrix());
  60354. _this.refreshBoundingInfo();
  60355. _this._syncSubMeshes();
  60356. return _this;
  60357. }
  60358. /**
  60359. * Returns the string "InstancedMesh".
  60360. */
  60361. InstancedMesh.prototype.getClassName = function () {
  60362. return "InstancedMesh";
  60363. };
  60364. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60365. // Methods
  60366. get: function () {
  60367. return this._sourceMesh.receiveShadows;
  60368. },
  60369. enumerable: true,
  60370. configurable: true
  60371. });
  60372. Object.defineProperty(InstancedMesh.prototype, "material", {
  60373. get: function () {
  60374. return this._sourceMesh.material;
  60375. },
  60376. enumerable: true,
  60377. configurable: true
  60378. });
  60379. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60380. get: function () {
  60381. return this._sourceMesh.visibility;
  60382. },
  60383. enumerable: true,
  60384. configurable: true
  60385. });
  60386. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60387. get: function () {
  60388. return this._sourceMesh.skeleton;
  60389. },
  60390. enumerable: true,
  60391. configurable: true
  60392. });
  60393. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60394. get: function () {
  60395. return this._sourceMesh.renderingGroupId;
  60396. },
  60397. set: function (value) {
  60398. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60399. return;
  60400. }
  60401. //no-op with warning
  60402. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60403. },
  60404. enumerable: true,
  60405. configurable: true
  60406. });
  60407. /**
  60408. * Returns the total number of vertices (integer).
  60409. */
  60410. InstancedMesh.prototype.getTotalVertices = function () {
  60411. return this._sourceMesh.getTotalVertices();
  60412. };
  60413. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60414. get: function () {
  60415. return this._sourceMesh;
  60416. },
  60417. enumerable: true,
  60418. configurable: true
  60419. });
  60420. /**
  60421. * Is this node ready to be used/rendered
  60422. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60423. * @return {boolean} is it ready
  60424. */
  60425. InstancedMesh.prototype.isReady = function (completeCheck) {
  60426. if (completeCheck === void 0) { completeCheck = false; }
  60427. return this._sourceMesh.isReady(completeCheck, true);
  60428. };
  60429. /**
  60430. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60431. */
  60432. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60433. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60434. };
  60435. /**
  60436. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60437. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60438. * The `data` are either a numeric array either a Float32Array.
  60439. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60440. * 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).
  60441. * Note that a new underlying VertexBuffer object is created each call.
  60442. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60443. *
  60444. * Possible `kind` values :
  60445. * - BABYLON.VertexBuffer.PositionKind
  60446. * - BABYLON.VertexBuffer.UVKind
  60447. * - BABYLON.VertexBuffer.UV2Kind
  60448. * - BABYLON.VertexBuffer.UV3Kind
  60449. * - BABYLON.VertexBuffer.UV4Kind
  60450. * - BABYLON.VertexBuffer.UV5Kind
  60451. * - BABYLON.VertexBuffer.UV6Kind
  60452. * - BABYLON.VertexBuffer.ColorKind
  60453. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60454. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60455. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60456. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60457. *
  60458. * Returns the Mesh.
  60459. */
  60460. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60461. if (this.sourceMesh) {
  60462. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60463. }
  60464. return this.sourceMesh;
  60465. };
  60466. /**
  60467. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60468. * If the mesh has no geometry, it is simply returned as it is.
  60469. * The `data` are either a numeric array either a Float32Array.
  60470. * No new underlying VertexBuffer object is created.
  60471. * 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.
  60472. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60473. *
  60474. * Possible `kind` values :
  60475. * - BABYLON.VertexBuffer.PositionKind
  60476. * - BABYLON.VertexBuffer.UVKind
  60477. * - BABYLON.VertexBuffer.UV2Kind
  60478. * - BABYLON.VertexBuffer.UV3Kind
  60479. * - BABYLON.VertexBuffer.UV4Kind
  60480. * - BABYLON.VertexBuffer.UV5Kind
  60481. * - BABYLON.VertexBuffer.UV6Kind
  60482. * - BABYLON.VertexBuffer.ColorKind
  60483. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60484. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60485. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60486. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60487. *
  60488. * Returns the Mesh.
  60489. */
  60490. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60491. if (this.sourceMesh) {
  60492. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60493. }
  60494. return this.sourceMesh;
  60495. };
  60496. /**
  60497. * Sets the mesh indices.
  60498. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60499. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60500. * This method creates a new index buffer each call.
  60501. * Returns the Mesh.
  60502. */
  60503. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60504. if (totalVertices === void 0) { totalVertices = null; }
  60505. if (this.sourceMesh) {
  60506. this.sourceMesh.setIndices(indices, totalVertices);
  60507. }
  60508. return this.sourceMesh;
  60509. };
  60510. /**
  60511. * Boolean : True if the mesh owns the requested kind of data.
  60512. */
  60513. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60514. return this._sourceMesh.isVerticesDataPresent(kind);
  60515. };
  60516. /**
  60517. * Returns an array of indices (IndicesArray).
  60518. */
  60519. InstancedMesh.prototype.getIndices = function () {
  60520. return this._sourceMesh.getIndices();
  60521. };
  60522. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60523. get: function () {
  60524. return this._sourceMesh._positions;
  60525. },
  60526. enumerable: true,
  60527. configurable: true
  60528. });
  60529. /**
  60530. * Sets a new updated BoundingInfo to the mesh.
  60531. * Returns the mesh.
  60532. */
  60533. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60534. var meshBB = this._sourceMesh.getBoundingInfo();
  60535. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60536. this._updateBoundingInfo();
  60537. return this;
  60538. };
  60539. InstancedMesh.prototype._preActivate = function () {
  60540. if (this._currentLOD) {
  60541. this._currentLOD._preActivate();
  60542. }
  60543. return this;
  60544. };
  60545. InstancedMesh.prototype._activate = function (renderId) {
  60546. if (this._currentLOD) {
  60547. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60548. }
  60549. return this;
  60550. };
  60551. /**
  60552. * Returns the current associated LOD AbstractMesh.
  60553. */
  60554. InstancedMesh.prototype.getLOD = function (camera) {
  60555. if (!camera) {
  60556. return this;
  60557. }
  60558. var boundingInfo = this.getBoundingInfo();
  60559. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60560. if (this._currentLOD === this.sourceMesh) {
  60561. return this;
  60562. }
  60563. return this._currentLOD;
  60564. };
  60565. InstancedMesh.prototype._syncSubMeshes = function () {
  60566. this.releaseSubMeshes();
  60567. if (this._sourceMesh.subMeshes) {
  60568. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60569. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60570. }
  60571. }
  60572. return this;
  60573. };
  60574. InstancedMesh.prototype._generatePointsArray = function () {
  60575. return this._sourceMesh._generatePointsArray();
  60576. };
  60577. /**
  60578. * Creates a new InstancedMesh from the current mesh.
  60579. * - name (string) : the cloned mesh name
  60580. * - newParent (optional Node) : the optional Node to parent the clone to.
  60581. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60582. *
  60583. * Returns the clone.
  60584. */
  60585. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60586. var result = this._sourceMesh.createInstance(name);
  60587. // Deep copy
  60588. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60589. // Bounding info
  60590. this.refreshBoundingInfo();
  60591. // Parent
  60592. if (newParent) {
  60593. result.parent = newParent;
  60594. }
  60595. if (!doNotCloneChildren) {
  60596. // Children
  60597. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60598. var mesh = this.getScene().meshes[index];
  60599. if (mesh.parent === this) {
  60600. mesh.clone(mesh.name, result);
  60601. }
  60602. }
  60603. }
  60604. result.computeWorldMatrix(true);
  60605. return result;
  60606. };
  60607. /**
  60608. * Disposes the InstancedMesh.
  60609. * Returns nothing.
  60610. */
  60611. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60612. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60613. // Remove from mesh
  60614. var index = this._sourceMesh.instances.indexOf(this);
  60615. this._sourceMesh.instances.splice(index, 1);
  60616. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60617. };
  60618. return InstancedMesh;
  60619. }(BABYLON.AbstractMesh));
  60620. BABYLON.InstancedMesh = InstancedMesh;
  60621. })(BABYLON || (BABYLON = {}));
  60622. //# sourceMappingURL=babylon.instancedMesh.js.map
  60623. var BABYLON;
  60624. (function (BABYLON) {
  60625. var LinesMesh = /** @class */ (function (_super) {
  60626. __extends(LinesMesh, _super);
  60627. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60628. if (scene === void 0) { scene = null; }
  60629. if (parent === void 0) { parent = null; }
  60630. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60631. _this.useVertexColor = useVertexColor;
  60632. _this.useVertexAlpha = useVertexAlpha;
  60633. _this.color = new BABYLON.Color3(1, 1, 1);
  60634. _this.alpha = 1;
  60635. if (source) {
  60636. _this.color = source.color.clone();
  60637. _this.alpha = source.alpha;
  60638. _this.useVertexColor = source.useVertexColor;
  60639. _this.useVertexAlpha = source.useVertexAlpha;
  60640. }
  60641. _this._intersectionThreshold = 0.1;
  60642. var defines = [];
  60643. var options = {
  60644. attributes: [BABYLON.VertexBuffer.PositionKind],
  60645. uniforms: ["world", "viewProjection"],
  60646. needAlphaBlending: true,
  60647. defines: defines
  60648. };
  60649. if (useVertexAlpha === false) {
  60650. options.needAlphaBlending = false;
  60651. }
  60652. if (!useVertexColor) {
  60653. options.uniforms.push("color");
  60654. }
  60655. else {
  60656. options.defines.push("#define VERTEXCOLOR");
  60657. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60658. }
  60659. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60660. return _this;
  60661. }
  60662. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60663. /**
  60664. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60665. * This margin is expressed in world space coordinates, so its value may vary.
  60666. * Default value is 0.1
  60667. * @returns the intersection Threshold value.
  60668. */
  60669. get: function () {
  60670. return this._intersectionThreshold;
  60671. },
  60672. /**
  60673. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60674. * This margin is expressed in world space coordinates, so its value may vary.
  60675. * @param value the new threshold to apply
  60676. */
  60677. set: function (value) {
  60678. if (this._intersectionThreshold === value) {
  60679. return;
  60680. }
  60681. this._intersectionThreshold = value;
  60682. if (this.geometry) {
  60683. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60684. }
  60685. },
  60686. enumerable: true,
  60687. configurable: true
  60688. });
  60689. /**
  60690. * Returns the string "LineMesh"
  60691. */
  60692. LinesMesh.prototype.getClassName = function () {
  60693. return "LinesMesh";
  60694. };
  60695. Object.defineProperty(LinesMesh.prototype, "material", {
  60696. get: function () {
  60697. return this._colorShader;
  60698. },
  60699. set: function (value) {
  60700. // Do nothing
  60701. },
  60702. enumerable: true,
  60703. configurable: true
  60704. });
  60705. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60706. get: function () {
  60707. return false;
  60708. },
  60709. enumerable: true,
  60710. configurable: true
  60711. });
  60712. LinesMesh.prototype.createInstance = function (name) {
  60713. throw new Error("LinesMeshes do not support createInstance.");
  60714. };
  60715. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60716. if (!this._geometry) {
  60717. return this;
  60718. }
  60719. // VBOs
  60720. this._geometry._bind(this._colorShader.getEffect());
  60721. // Color
  60722. if (!this.useVertexColor) {
  60723. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60724. }
  60725. return this;
  60726. };
  60727. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60728. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60729. return this;
  60730. }
  60731. var engine = this.getScene().getEngine();
  60732. // Draw order
  60733. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60734. return this;
  60735. };
  60736. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60737. this._colorShader.dispose();
  60738. _super.prototype.dispose.call(this, doNotRecurse);
  60739. };
  60740. /**
  60741. * Returns a new LineMesh object cloned from the current one.
  60742. */
  60743. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60744. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60745. };
  60746. return LinesMesh;
  60747. }(BABYLON.Mesh));
  60748. BABYLON.LinesMesh = LinesMesh;
  60749. })(BABYLON || (BABYLON = {}));
  60750. //# sourceMappingURL=babylon.linesMesh.js.map
  60751. var BABYLON;
  60752. (function (BABYLON) {
  60753. /**
  60754. * Class containing static functions to help procedurally build meshes
  60755. */
  60756. var MeshBuilder = /** @class */ (function () {
  60757. function MeshBuilder() {
  60758. }
  60759. MeshBuilder.updateSideOrientation = function (orientation) {
  60760. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60761. return BABYLON.Mesh.DOUBLESIDE;
  60762. }
  60763. if (orientation === undefined || orientation === null) {
  60764. return BABYLON.Mesh.FRONTSIDE;
  60765. }
  60766. return orientation;
  60767. };
  60768. /**
  60769. * Creates a box mesh
  60770. * * The parameter `size` sets the size (float) of each box side (default 1)
  60771. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60772. * * 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)
  60773. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60774. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60775. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60776. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60777. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60778. * @param name defines the name of the mesh
  60779. * @param options defines the options used to create the mesh
  60780. * @param scene defines the hosting scene
  60781. * @returns the box mesh
  60782. */
  60783. MeshBuilder.CreateBox = function (name, options, scene) {
  60784. if (scene === void 0) { scene = null; }
  60785. var box = new BABYLON.Mesh(name, scene);
  60786. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60787. box._originalBuilderSideOrientation = options.sideOrientation;
  60788. var vertexData = BABYLON.VertexData.CreateBox(options);
  60789. vertexData.applyToMesh(box, options.updatable);
  60790. return box;
  60791. };
  60792. /**
  60793. * Creates a sphere mesh
  60794. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60795. * * 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`)
  60796. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60797. * * 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
  60798. * * 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)
  60799. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60800. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60801. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60802. * @param name defines the name of the mesh
  60803. * @param options defines the options used to create the mesh
  60804. * @param scene defines the hosting scene
  60805. * @returns the sphere mesh
  60806. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60807. */
  60808. MeshBuilder.CreateSphere = function (name, options, scene) {
  60809. var sphere = new BABYLON.Mesh(name, scene);
  60810. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60811. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60812. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60813. vertexData.applyToMesh(sphere, options.updatable);
  60814. return sphere;
  60815. };
  60816. /**
  60817. * Creates a plane polygonal mesh. By default, this is a disc
  60818. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60819. * * 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
  60820. * * 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
  60821. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60822. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60823. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60824. * @param name defines the name of the mesh
  60825. * @param options defines the options used to create the mesh
  60826. * @param scene defines the hosting scene
  60827. * @returns the plane polygonal mesh
  60828. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60829. */
  60830. MeshBuilder.CreateDisc = function (name, options, scene) {
  60831. if (scene === void 0) { scene = null; }
  60832. var disc = new BABYLON.Mesh(name, scene);
  60833. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60834. disc._originalBuilderSideOrientation = options.sideOrientation;
  60835. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60836. vertexData.applyToMesh(disc, options.updatable);
  60837. return disc;
  60838. };
  60839. /**
  60840. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60841. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60842. * * 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`)
  60843. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60844. * * 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
  60845. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60846. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60847. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60848. * @param name defines the name of the mesh
  60849. * @param options defines the options used to create the mesh
  60850. * @param scene defines the hosting scene
  60851. * @returns the icosahedron mesh
  60852. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60853. */
  60854. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60855. var sphere = new BABYLON.Mesh(name, scene);
  60856. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60857. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60858. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60859. vertexData.applyToMesh(sphere, options.updatable);
  60860. return sphere;
  60861. };
  60862. ;
  60863. /**
  60864. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60865. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60866. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60867. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60868. * * 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
  60869. * * 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
  60870. * * 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
  60871. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60872. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60873. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60874. * * 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
  60875. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60876. * * 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
  60877. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60878. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60879. * @param name defines the name of the mesh
  60880. * @param options defines the options used to create the mesh
  60881. * @param scene defines the hosting scene
  60882. * @returns the ribbon mesh
  60883. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60884. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60885. */
  60886. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60887. if (scene === void 0) { scene = null; }
  60888. var pathArray = options.pathArray;
  60889. var closeArray = options.closeArray;
  60890. var closePath = options.closePath;
  60891. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60892. var instance = options.instance;
  60893. var updatable = options.updatable;
  60894. if (instance) { // existing ribbon instance update
  60895. // positionFunction : ribbon case
  60896. // only pathArray and sideOrientation parameters are taken into account for positions update
  60897. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60898. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60899. var positionFunction = function (positions) {
  60900. var minlg = pathArray[0].length;
  60901. var i = 0;
  60902. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60903. for (var si = 1; si <= ns; si++) {
  60904. for (var p = 0; p < pathArray.length; p++) {
  60905. var path = pathArray[p];
  60906. var l = path.length;
  60907. minlg = (minlg < l) ? minlg : l;
  60908. var j = 0;
  60909. while (j < minlg) {
  60910. positions[i] = path[j].x;
  60911. positions[i + 1] = path[j].y;
  60912. positions[i + 2] = path[j].z;
  60913. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60914. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60915. }
  60916. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60917. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60918. }
  60919. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60920. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60921. }
  60922. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60923. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60924. }
  60925. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60926. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60927. }
  60928. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60929. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60930. }
  60931. j++;
  60932. i += 3;
  60933. }
  60934. if (instance._closePath) {
  60935. positions[i] = path[0].x;
  60936. positions[i + 1] = path[0].y;
  60937. positions[i + 2] = path[0].z;
  60938. i += 3;
  60939. }
  60940. }
  60941. }
  60942. };
  60943. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60944. positionFunction(positions);
  60945. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60946. instance._boundingInfo.update(instance._worldMatrix);
  60947. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60948. if (options.colors) {
  60949. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60950. for (var c = 0; c < options.colors.length; c++) {
  60951. colors[c * 4] = options.colors[c].r;
  60952. colors[c * 4 + 1] = options.colors[c].g;
  60953. colors[c * 4 + 2] = options.colors[c].b;
  60954. colors[c * 4 + 3] = options.colors[c].a;
  60955. }
  60956. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60957. }
  60958. if (options.uvs) {
  60959. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60960. for (var i = 0; i < options.uvs.length; i++) {
  60961. uvs[i * 2] = options.uvs[i].x;
  60962. uvs[i * 2 + 1] = options.uvs[i].y;
  60963. }
  60964. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60965. }
  60966. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60967. var indices = instance.getIndices();
  60968. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60969. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60970. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60971. if (instance._closePath) {
  60972. var indexFirst = 0;
  60973. var indexLast = 0;
  60974. for (var p = 0; p < pathArray.length; p++) {
  60975. indexFirst = instance._idx[p] * 3;
  60976. if (p + 1 < pathArray.length) {
  60977. indexLast = (instance._idx[p + 1] - 1) * 3;
  60978. }
  60979. else {
  60980. indexLast = normals.length - 3;
  60981. }
  60982. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60983. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60984. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60985. normals[indexLast] = normals[indexFirst];
  60986. normals[indexLast + 1] = normals[indexFirst + 1];
  60987. normals[indexLast + 2] = normals[indexFirst + 2];
  60988. }
  60989. }
  60990. if (!(instance.areNormalsFrozen)) {
  60991. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60992. }
  60993. }
  60994. return instance;
  60995. }
  60996. else { // new ribbon creation
  60997. var ribbon = new BABYLON.Mesh(name, scene);
  60998. ribbon._originalBuilderSideOrientation = sideOrientation;
  60999. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61000. if (closePath) {
  61001. ribbon._idx = vertexData._idx;
  61002. }
  61003. ribbon._closePath = closePath;
  61004. ribbon._closeArray = closeArray;
  61005. vertexData.applyToMesh(ribbon, updatable);
  61006. return ribbon;
  61007. }
  61008. };
  61009. /**
  61010. * Creates a cylinder or a cone mesh
  61011. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61012. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61013. * * 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.
  61014. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61015. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61016. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61017. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61018. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61019. * * 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).
  61020. * * 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
  61021. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61022. * * 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
  61023. * * 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.
  61024. * * If `enclose` is false, a ring surface is one element.
  61025. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61026. * * 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
  61027. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61028. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61029. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61030. * @param name defines the name of the mesh
  61031. * @param options defines the options used to create the mesh
  61032. * @param scene defines the hosting scene
  61033. * @returns the cylinder mesh
  61034. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61035. */
  61036. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61037. var cylinder = new BABYLON.Mesh(name, scene);
  61038. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61039. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61040. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61041. vertexData.applyToMesh(cylinder, options.updatable);
  61042. return cylinder;
  61043. };
  61044. /**
  61045. * Creates a torus mesh
  61046. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61047. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61048. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61049. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61050. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61051. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61052. * @param name defines the name of the mesh
  61053. * @param options defines the options used to create the mesh
  61054. * @param scene defines the hosting scene
  61055. * @returns the torus mesh
  61056. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61057. */
  61058. MeshBuilder.CreateTorus = function (name, options, scene) {
  61059. var torus = new BABYLON.Mesh(name, scene);
  61060. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61061. torus._originalBuilderSideOrientation = options.sideOrientation;
  61062. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61063. vertexData.applyToMesh(torus, options.updatable);
  61064. return torus;
  61065. };
  61066. /**
  61067. * Creates a torus knot mesh
  61068. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61069. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61070. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61071. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61072. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61073. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61074. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61075. * @param name defines the name of the mesh
  61076. * @param options defines the options used to create the mesh
  61077. * @param scene defines the hosting scene
  61078. * @returns the torus knot mesh
  61079. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61080. */
  61081. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61082. var torusKnot = new BABYLON.Mesh(name, scene);
  61083. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61084. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61085. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61086. vertexData.applyToMesh(torusKnot, options.updatable);
  61087. return torusKnot;
  61088. };
  61089. /**
  61090. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61091. * * 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
  61092. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61093. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61094. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61095. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61096. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61097. * * 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
  61098. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61099. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61100. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61101. * @param name defines the name of the new line system
  61102. * @param options defines the options used to create the line system
  61103. * @param scene defines the hosting scene
  61104. * @returns a new line system mesh
  61105. */
  61106. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61107. var instance = options.instance;
  61108. var lines = options.lines;
  61109. var colors = options.colors;
  61110. if (instance) { // lines update
  61111. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61112. var vertexColor;
  61113. var lineColors;
  61114. if (colors) {
  61115. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61116. }
  61117. var i = 0;
  61118. var c = 0;
  61119. for (var l = 0; l < lines.length; l++) {
  61120. var points = lines[l];
  61121. for (var p = 0; p < points.length; p++) {
  61122. positions[i] = points[p].x;
  61123. positions[i + 1] = points[p].y;
  61124. positions[i + 2] = points[p].z;
  61125. if (colors && vertexColor) {
  61126. lineColors = colors[l];
  61127. vertexColor[c] = lineColors[p].r;
  61128. vertexColor[c + 1] = lineColors[p].g;
  61129. vertexColor[c + 2] = lineColors[p].b;
  61130. vertexColor[c + 3] = lineColors[p].a;
  61131. c += 4;
  61132. }
  61133. i += 3;
  61134. }
  61135. }
  61136. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61137. if (colors && vertexColor) {
  61138. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61139. }
  61140. return instance;
  61141. }
  61142. // line system creation
  61143. var useVertexColor = (colors) ? true : false;
  61144. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61145. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61146. vertexData.applyToMesh(lineSystem, options.updatable);
  61147. return lineSystem;
  61148. };
  61149. /**
  61150. * Creates a line mesh
  61151. * 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
  61152. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61153. * * The parameter `points` is an array successive Vector3
  61154. * * 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
  61155. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61156. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61157. * * When updating an instance, remember that only point positions can change, not the number of points
  61158. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61159. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61160. * @param name defines the name of the new line system
  61161. * @param options defines the options used to create the line system
  61162. * @param scene defines the hosting scene
  61163. * @returns a new line mesh
  61164. */
  61165. MeshBuilder.CreateLines = function (name, options, scene) {
  61166. if (scene === void 0) { scene = null; }
  61167. var colors = (options.colors) ? [options.colors] : null;
  61168. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61169. return lines;
  61170. };
  61171. /**
  61172. * Creates a dashed line mesh
  61173. * * 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
  61174. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61175. * * The parameter `points` is an array successive Vector3
  61176. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61177. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61178. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61179. * * 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
  61180. * * When updating an instance, remember that only point positions can change, not the number of points
  61181. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61182. * @param name defines the name of the mesh
  61183. * @param options defines the options used to create the mesh
  61184. * @param scene defines the hosting scene
  61185. * @returns the dashed line mesh
  61186. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61187. */
  61188. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61189. if (scene === void 0) { scene = null; }
  61190. var points = options.points;
  61191. var instance = options.instance;
  61192. var gapSize = options.gapSize || 1;
  61193. var dashSize = options.dashSize || 3;
  61194. if (instance) { // dashed lines update
  61195. var positionFunction = function (positions) {
  61196. var curvect = BABYLON.Vector3.Zero();
  61197. var nbSeg = positions.length / 6;
  61198. var lg = 0;
  61199. var nb = 0;
  61200. var shft = 0;
  61201. var dashshft = 0;
  61202. var curshft = 0;
  61203. var p = 0;
  61204. var i = 0;
  61205. var j = 0;
  61206. for (i = 0; i < points.length - 1; i++) {
  61207. points[i + 1].subtractToRef(points[i], curvect);
  61208. lg += curvect.length();
  61209. }
  61210. shft = lg / nbSeg;
  61211. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61212. for (i = 0; i < points.length - 1; i++) {
  61213. points[i + 1].subtractToRef(points[i], curvect);
  61214. nb = Math.floor(curvect.length() / shft);
  61215. curvect.normalize();
  61216. j = 0;
  61217. while (j < nb && p < positions.length) {
  61218. curshft = shft * j;
  61219. positions[p] = points[i].x + curshft * curvect.x;
  61220. positions[p + 1] = points[i].y + curshft * curvect.y;
  61221. positions[p + 2] = points[i].z + curshft * curvect.z;
  61222. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61223. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61224. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61225. p += 6;
  61226. j++;
  61227. }
  61228. }
  61229. while (p < positions.length) {
  61230. positions[p] = points[i].x;
  61231. positions[p + 1] = points[i].y;
  61232. positions[p + 2] = points[i].z;
  61233. p += 3;
  61234. }
  61235. };
  61236. instance.updateMeshPositions(positionFunction, false);
  61237. return instance;
  61238. }
  61239. // dashed lines creation
  61240. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61241. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61242. vertexData.applyToMesh(dashedLines, options.updatable);
  61243. dashedLines.dashSize = dashSize;
  61244. dashedLines.gapSize = gapSize;
  61245. return dashedLines;
  61246. };
  61247. /**
  61248. * 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.
  61249. * * 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.
  61250. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61251. * * 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.
  61252. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61253. * * 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
  61254. * * 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
  61255. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61256. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61257. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61258. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61259. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61260. * @param name defines the name of the mesh
  61261. * @param options defines the options used to create the mesh
  61262. * @param scene defines the hosting scene
  61263. * @returns the extruded shape mesh
  61264. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61265. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61266. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61267. */
  61268. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61269. if (scene === void 0) { scene = null; }
  61270. var path = options.path;
  61271. var shape = options.shape;
  61272. var scale = options.scale || 1;
  61273. var rotation = options.rotation || 0;
  61274. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61275. var updatable = options.updatable;
  61276. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61277. var instance = options.instance || null;
  61278. var invertUV = options.invertUV || false;
  61279. 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);
  61280. };
  61281. /**
  61282. * Creates an custom extruded shape mesh.
  61283. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61284. * * 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.
  61285. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61286. * * 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
  61287. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61288. * * 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
  61289. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61290. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61291. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61292. * * 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
  61293. * * 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
  61294. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61295. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61296. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61297. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61298. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61299. * @param name defines the name of the mesh
  61300. * @param options defines the options used to create the mesh
  61301. * @param scene defines the hosting scene
  61302. * @returns the custom extruded shape mesh
  61303. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61304. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61305. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61306. */
  61307. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61308. var path = options.path;
  61309. var shape = options.shape;
  61310. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61311. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61312. var ribbonCloseArray = options.ribbonCloseArray || false;
  61313. var ribbonClosePath = options.ribbonClosePath || false;
  61314. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61315. var updatable = options.updatable;
  61316. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61317. var instance = options.instance;
  61318. var invertUV = options.invertUV || false;
  61319. 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);
  61320. };
  61321. /**
  61322. * Creates lathe mesh.
  61323. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61324. * * 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
  61325. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61326. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61327. * * 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
  61328. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61329. * * 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
  61330. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61331. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61332. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61333. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61334. * @param name defines the name of the mesh
  61335. * @param options defines the options used to create the mesh
  61336. * @param scene defines the hosting scene
  61337. * @returns the lathe mesh
  61338. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61339. */
  61340. MeshBuilder.CreateLathe = function (name, options, scene) {
  61341. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61342. var closed = (options.closed === undefined) ? true : options.closed;
  61343. var shape = options.shape;
  61344. var radius = options.radius || 1;
  61345. var tessellation = options.tessellation || 64;
  61346. var updatable = options.updatable;
  61347. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61348. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61349. var pi2 = Math.PI * 2;
  61350. var paths = new Array();
  61351. var invertUV = options.invertUV || false;
  61352. var i = 0;
  61353. var p = 0;
  61354. var step = pi2 / tessellation * arc;
  61355. var rotated;
  61356. var path = new Array();
  61357. for (i = 0; i <= tessellation; i++) {
  61358. var path = [];
  61359. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61360. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61361. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61362. }
  61363. for (p = 0; p < shape.length; p++) {
  61364. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61365. path.push(rotated);
  61366. }
  61367. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61368. 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));
  61369. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61370. }
  61371. paths.push(path);
  61372. }
  61373. // lathe ribbon
  61374. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61375. return lathe;
  61376. };
  61377. /**
  61378. * Creates a plane mesh
  61379. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61380. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61381. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61382. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61383. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61384. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61385. * @param name defines the name of the mesh
  61386. * @param options defines the options used to create the mesh
  61387. * @param scene defines the hosting scene
  61388. * @returns the plane mesh
  61389. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61390. */
  61391. MeshBuilder.CreatePlane = function (name, options, scene) {
  61392. var plane = new BABYLON.Mesh(name, scene);
  61393. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61394. plane._originalBuilderSideOrientation = options.sideOrientation;
  61395. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61396. vertexData.applyToMesh(plane, options.updatable);
  61397. if (options.sourcePlane) {
  61398. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61399. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61400. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61401. plane.rotate(vectorProduct, product);
  61402. }
  61403. return plane;
  61404. };
  61405. /**
  61406. * Creates a ground mesh
  61407. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61408. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61409. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61410. * @param name defines the name of the mesh
  61411. * @param options defines the options used to create the mesh
  61412. * @param scene defines the hosting scene
  61413. * @returns the ground mesh
  61414. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61415. */
  61416. MeshBuilder.CreateGround = function (name, options, scene) {
  61417. var ground = new BABYLON.GroundMesh(name, scene);
  61418. ground._setReady(false);
  61419. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61420. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61421. ground._width = options.width || 1;
  61422. ground._height = options.height || 1;
  61423. ground._maxX = ground._width / 2;
  61424. ground._maxZ = ground._height / 2;
  61425. ground._minX = -ground._maxX;
  61426. ground._minZ = -ground._maxZ;
  61427. var vertexData = BABYLON.VertexData.CreateGround(options);
  61428. vertexData.applyToMesh(ground, options.updatable);
  61429. ground._setReady(true);
  61430. return ground;
  61431. };
  61432. /**
  61433. * Creates a tiled ground mesh
  61434. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61435. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61436. * * 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
  61437. * * 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
  61438. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61439. * @param name defines the name of the mesh
  61440. * @param options defines the options used to create the mesh
  61441. * @param scene defines the hosting scene
  61442. * @returns the tiled ground mesh
  61443. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61444. */
  61445. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61446. var tiledGround = new BABYLON.Mesh(name, scene);
  61447. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61448. vertexData.applyToMesh(tiledGround, options.updatable);
  61449. return tiledGround;
  61450. };
  61451. /**
  61452. * Creates a ground mesh from a height map
  61453. * * The parameter `url` sets the URL of the height map image resource.
  61454. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61455. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61456. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61457. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61458. * * 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.
  61459. * * 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).
  61460. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61461. * @param name defines the name of the mesh
  61462. * @param url defines the url to the height map
  61463. * @param options defines the options used to create the mesh
  61464. * @param scene defines the hosting scene
  61465. * @returns the ground mesh
  61466. * @see http://doc.babylonjs.com/babylon101/height_map
  61467. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61468. */
  61469. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61470. var width = options.width || 10.0;
  61471. var height = options.height || 10.0;
  61472. var subdivisions = options.subdivisions || 1 | 0;
  61473. var minHeight = options.minHeight || 0.0;
  61474. var maxHeight = options.maxHeight || 1.0;
  61475. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61476. var updatable = options.updatable;
  61477. var onReady = options.onReady;
  61478. var ground = new BABYLON.GroundMesh(name, scene);
  61479. ground._subdivisionsX = subdivisions;
  61480. ground._subdivisionsY = subdivisions;
  61481. ground._width = width;
  61482. ground._height = height;
  61483. ground._maxX = ground._width / 2.0;
  61484. ground._maxZ = ground._height / 2.0;
  61485. ground._minX = -ground._maxX;
  61486. ground._minZ = -ground._maxZ;
  61487. ground._setReady(false);
  61488. var onload = function (img) {
  61489. // Getting height map data
  61490. var canvas = document.createElement("canvas");
  61491. var context = canvas.getContext("2d");
  61492. if (!context) {
  61493. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61494. }
  61495. if (scene.isDisposed) {
  61496. return;
  61497. }
  61498. var bufferWidth = img.width;
  61499. var bufferHeight = img.height;
  61500. canvas.width = bufferWidth;
  61501. canvas.height = bufferHeight;
  61502. context.drawImage(img, 0, 0);
  61503. // Create VertexData from map data
  61504. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61505. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61506. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61507. width: width, height: height,
  61508. subdivisions: subdivisions,
  61509. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61510. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61511. });
  61512. vertexData.applyToMesh(ground, updatable);
  61513. //execute ready callback, if set
  61514. if (onReady) {
  61515. onReady(ground);
  61516. }
  61517. ground._setReady(true);
  61518. };
  61519. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61520. return ground;
  61521. };
  61522. /**
  61523. * Creates a polygon mesh
  61524. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61525. * * 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
  61526. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61527. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61528. * * 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)
  61529. * * Remember you can only change the shape positions, not their number when updating a polygon
  61530. * @param name defines the name of the mesh
  61531. * @param options defines the options used to create the mesh
  61532. * @param scene defines the hosting scene
  61533. * @returns the polygon mesh
  61534. */
  61535. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61536. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61537. var shape = options.shape;
  61538. var holes = options.holes || [];
  61539. var depth = options.depth || 0;
  61540. var contours = [];
  61541. var hole = [];
  61542. for (var i = 0; i < shape.length; i++) {
  61543. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61544. }
  61545. var epsilon = 0.00000001;
  61546. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61547. contours.pop();
  61548. }
  61549. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61550. for (var hNb = 0; hNb < holes.length; hNb++) {
  61551. hole = [];
  61552. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61553. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61554. }
  61555. polygonTriangulation.addHole(hole);
  61556. }
  61557. var polygon = polygonTriangulation.build(options.updatable, depth);
  61558. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61559. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61560. vertexData.applyToMesh(polygon, options.updatable);
  61561. return polygon;
  61562. };
  61563. ;
  61564. /**
  61565. * Creates an extruded polygon mesh, with depth in the Y direction.
  61566. * * 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)
  61567. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61568. * @param name defines the name of the mesh
  61569. * @param options defines the options used to create the mesh
  61570. * @param scene defines the hosting scene
  61571. * @returns the polygon mesh
  61572. */
  61573. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61574. return MeshBuilder.CreatePolygon(name, options, scene);
  61575. };
  61576. ;
  61577. /**
  61578. * Creates a tube mesh.
  61579. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61580. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61581. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61582. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61583. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61584. * * 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)
  61585. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61586. * * 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
  61587. * * 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
  61588. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61589. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61590. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61591. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61592. * @param name defines the name of the mesh
  61593. * @param options defines the options used to create the mesh
  61594. * @param scene defines the hosting scene
  61595. * @returns the tube mesh
  61596. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61597. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61598. */
  61599. MeshBuilder.CreateTube = function (name, options, scene) {
  61600. var path = options.path;
  61601. var instance = options.instance;
  61602. var radius = 1.0;
  61603. if (instance) {
  61604. radius = instance.radius;
  61605. }
  61606. if (options.radius !== undefined) {
  61607. radius = options.radius;
  61608. }
  61609. ;
  61610. var tessellation = options.tessellation || 64 | 0;
  61611. var radiusFunction = options.radiusFunction || null;
  61612. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61613. var invertUV = options.invertUV || false;
  61614. var updatable = options.updatable;
  61615. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61616. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61617. // tube geometry
  61618. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61619. var tangents = path3D.getTangents();
  61620. var normals = path3D.getNormals();
  61621. var distances = path3D.getDistances();
  61622. var pi2 = Math.PI * 2;
  61623. var step = pi2 / tessellation * arc;
  61624. var returnRadius = function () { return radius; };
  61625. var radiusFunctionFinal = radiusFunction || returnRadius;
  61626. var circlePath;
  61627. var rad;
  61628. var normal;
  61629. var rotated;
  61630. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61631. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61632. for (var i = 0; i < path.length; i++) {
  61633. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61634. circlePath = Array(); // current circle array
  61635. normal = normals[i]; // current normal
  61636. for (var t = 0; t < tessellation; t++) {
  61637. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61638. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61639. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61640. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61641. circlePath[t] = rotated;
  61642. }
  61643. circlePaths[index] = circlePath;
  61644. index++;
  61645. }
  61646. // cap
  61647. var capPath = function (nbPoints, pathIndex) {
  61648. var pointCap = Array();
  61649. for (var i = 0; i < nbPoints; i++) {
  61650. pointCap.push(path[pathIndex]);
  61651. }
  61652. return pointCap;
  61653. };
  61654. switch (cap) {
  61655. case BABYLON.Mesh.NO_CAP:
  61656. break;
  61657. case BABYLON.Mesh.CAP_START:
  61658. circlePaths[0] = capPath(tessellation, 0);
  61659. circlePaths[1] = circlePaths[2].slice(0);
  61660. break;
  61661. case BABYLON.Mesh.CAP_END:
  61662. circlePaths[index] = circlePaths[index - 1].slice(0);
  61663. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61664. break;
  61665. case BABYLON.Mesh.CAP_ALL:
  61666. circlePaths[0] = capPath(tessellation, 0);
  61667. circlePaths[1] = circlePaths[2].slice(0);
  61668. circlePaths[index] = circlePaths[index - 1].slice(0);
  61669. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61670. break;
  61671. default:
  61672. break;
  61673. }
  61674. return circlePaths;
  61675. };
  61676. var path3D;
  61677. var pathArray;
  61678. if (instance) { // tube update
  61679. var arc = options.arc || instance.arc;
  61680. path3D = (instance.path3D).update(path);
  61681. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61682. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61683. instance.path3D = path3D;
  61684. instance.pathArray = pathArray;
  61685. instance.arc = arc;
  61686. instance.radius = radius;
  61687. return instance;
  61688. }
  61689. // tube creation
  61690. path3D = new BABYLON.Path3D(path);
  61691. var newPathArray = new Array();
  61692. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61693. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61694. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61695. tube.pathArray = pathArray;
  61696. tube.path3D = path3D;
  61697. tube.tessellation = tessellation;
  61698. tube.cap = cap;
  61699. tube.arc = options.arc;
  61700. tube.radius = radius;
  61701. return tube;
  61702. };
  61703. /**
  61704. * Creates a polyhedron mesh
  61705. * * 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
  61706. * * The parameter `size` (positive float, default 1) sets the polygon size
  61707. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61708. * * 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`
  61709. * * 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
  61710. * * 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)`)
  61711. * * 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
  61712. * * 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
  61713. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61714. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61715. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61716. * @param name defines the name of the mesh
  61717. * @param options defines the options used to create the mesh
  61718. * @param scene defines the hosting scene
  61719. * @returns the polyhedron mesh
  61720. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61721. */
  61722. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61723. var polyhedron = new BABYLON.Mesh(name, scene);
  61724. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61725. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61726. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61727. vertexData.applyToMesh(polyhedron, options.updatable);
  61728. return polyhedron;
  61729. };
  61730. /**
  61731. * Creates a decal mesh.
  61732. * 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
  61733. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61734. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61735. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61736. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61737. * @param name defines the name of the mesh
  61738. * @param sourceMesh defines the mesh where the decal must be applied
  61739. * @param options defines the options used to create the mesh
  61740. * @param scene defines the hosting scene
  61741. * @returns the decal mesh
  61742. * @see http://doc.babylonjs.com/how_to/decals
  61743. */
  61744. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61745. var indices = sourceMesh.getIndices();
  61746. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61747. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61748. var position = options.position || BABYLON.Vector3.Zero();
  61749. var normal = options.normal || BABYLON.Vector3.Up();
  61750. var size = options.size || BABYLON.Vector3.One();
  61751. var angle = options.angle || 0;
  61752. // Getting correct rotation
  61753. if (!normal) {
  61754. var target = new BABYLON.Vector3(0, 0, 1);
  61755. var camera = sourceMesh.getScene().activeCamera;
  61756. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61757. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61758. }
  61759. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61760. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61761. var pitch = Math.atan2(normal.y, len);
  61762. // Matrix
  61763. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61764. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61765. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61766. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61767. var vertexData = new BABYLON.VertexData();
  61768. vertexData.indices = [];
  61769. vertexData.positions = [];
  61770. vertexData.normals = [];
  61771. vertexData.uvs = [];
  61772. var currentVertexDataIndex = 0;
  61773. var extractDecalVector3 = function (indexId) {
  61774. var result = new BABYLON.PositionNormalVertex();
  61775. if (!indices || !positions || !normals) {
  61776. return result;
  61777. }
  61778. var vertexId = indices[indexId];
  61779. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61780. // Send vector to decal local world
  61781. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61782. // Get normal
  61783. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61784. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61785. return result;
  61786. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61787. var clip = function (vertices, axis) {
  61788. if (vertices.length === 0) {
  61789. return vertices;
  61790. }
  61791. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61792. var clipVertices = function (v0, v1) {
  61793. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61794. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61795. };
  61796. var result = new Array();
  61797. for (var index = 0; index < vertices.length; index += 3) {
  61798. var v1Out;
  61799. var v2Out;
  61800. var v3Out;
  61801. var total = 0;
  61802. var nV1 = null;
  61803. var nV2 = null;
  61804. var nV3 = null;
  61805. var nV4 = null;
  61806. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61807. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61808. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61809. v1Out = d1 > 0;
  61810. v2Out = d2 > 0;
  61811. v3Out = d3 > 0;
  61812. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61813. switch (total) {
  61814. case 0:
  61815. result.push(vertices[index]);
  61816. result.push(vertices[index + 1]);
  61817. result.push(vertices[index + 2]);
  61818. break;
  61819. case 1:
  61820. if (v1Out) {
  61821. nV1 = vertices[index + 1];
  61822. nV2 = vertices[index + 2];
  61823. nV3 = clipVertices(vertices[index], nV1);
  61824. nV4 = clipVertices(vertices[index], nV2);
  61825. }
  61826. if (v2Out) {
  61827. nV1 = vertices[index];
  61828. nV2 = vertices[index + 2];
  61829. nV3 = clipVertices(vertices[index + 1], nV1);
  61830. nV4 = clipVertices(vertices[index + 1], nV2);
  61831. result.push(nV3);
  61832. result.push(nV2.clone());
  61833. result.push(nV1.clone());
  61834. result.push(nV2.clone());
  61835. result.push(nV3.clone());
  61836. result.push(nV4);
  61837. break;
  61838. }
  61839. if (v3Out) {
  61840. nV1 = vertices[index];
  61841. nV2 = vertices[index + 1];
  61842. nV3 = clipVertices(vertices[index + 2], nV1);
  61843. nV4 = clipVertices(vertices[index + 2], nV2);
  61844. }
  61845. if (nV1 && nV2 && nV3 && nV4) {
  61846. result.push(nV1.clone());
  61847. result.push(nV2.clone());
  61848. result.push(nV3);
  61849. result.push(nV4);
  61850. result.push(nV3.clone());
  61851. result.push(nV2.clone());
  61852. }
  61853. break;
  61854. case 2:
  61855. if (!v1Out) {
  61856. nV1 = vertices[index].clone();
  61857. nV2 = clipVertices(nV1, vertices[index + 1]);
  61858. nV3 = clipVertices(nV1, vertices[index + 2]);
  61859. result.push(nV1);
  61860. result.push(nV2);
  61861. result.push(nV3);
  61862. }
  61863. if (!v2Out) {
  61864. nV1 = vertices[index + 1].clone();
  61865. nV2 = clipVertices(nV1, vertices[index + 2]);
  61866. nV3 = clipVertices(nV1, vertices[index]);
  61867. result.push(nV1);
  61868. result.push(nV2);
  61869. result.push(nV3);
  61870. }
  61871. if (!v3Out) {
  61872. nV1 = vertices[index + 2].clone();
  61873. nV2 = clipVertices(nV1, vertices[index]);
  61874. nV3 = clipVertices(nV1, vertices[index + 1]);
  61875. result.push(nV1);
  61876. result.push(nV2);
  61877. result.push(nV3);
  61878. }
  61879. break;
  61880. case 3:
  61881. break;
  61882. }
  61883. }
  61884. return result;
  61885. };
  61886. for (var index = 0; index < indices.length; index += 3) {
  61887. var faceVertices = new Array();
  61888. faceVertices.push(extractDecalVector3(index));
  61889. faceVertices.push(extractDecalVector3(index + 1));
  61890. faceVertices.push(extractDecalVector3(index + 2));
  61891. // Clip
  61892. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61893. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61894. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61895. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61896. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61897. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61898. if (faceVertices.length === 0) {
  61899. continue;
  61900. }
  61901. // Add UVs and get back to world
  61902. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61903. var vertex = faceVertices[vIndex];
  61904. //TODO check for Int32Array | Uint32Array | Uint16Array
  61905. vertexData.indices.push(currentVertexDataIndex);
  61906. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61907. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61908. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61909. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61910. currentVertexDataIndex++;
  61911. }
  61912. }
  61913. // Return mesh
  61914. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61915. vertexData.applyToMesh(decal);
  61916. decal.position = position.clone();
  61917. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61918. return decal;
  61919. };
  61920. // Privates
  61921. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61922. // extrusion geometry
  61923. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61924. var tangents = path3D.getTangents();
  61925. var normals = path3D.getNormals();
  61926. var binormals = path3D.getBinormals();
  61927. var distances = path3D.getDistances();
  61928. var angle = 0;
  61929. var returnScale = function () { return scale !== null ? scale : 1; };
  61930. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61931. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61932. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61933. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61934. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61935. for (var i = 0; i < curve.length; i++) {
  61936. var shapePath = new Array();
  61937. var angleStep = rotate(i, distances[i]);
  61938. var scaleRatio = scl(i, distances[i]);
  61939. for (var p = 0; p < shape.length; p++) {
  61940. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61941. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61942. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61943. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61944. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61945. shapePath[p] = rotated;
  61946. }
  61947. shapePaths[index] = shapePath;
  61948. angle += angleStep;
  61949. index++;
  61950. }
  61951. // cap
  61952. var capPath = function (shapePath) {
  61953. var pointCap = Array();
  61954. var barycenter = BABYLON.Vector3.Zero();
  61955. var i;
  61956. for (i = 0; i < shapePath.length; i++) {
  61957. barycenter.addInPlace(shapePath[i]);
  61958. }
  61959. barycenter.scaleInPlace(1.0 / shapePath.length);
  61960. for (i = 0; i < shapePath.length; i++) {
  61961. pointCap.push(barycenter);
  61962. }
  61963. return pointCap;
  61964. };
  61965. switch (cap) {
  61966. case BABYLON.Mesh.NO_CAP:
  61967. break;
  61968. case BABYLON.Mesh.CAP_START:
  61969. shapePaths[0] = capPath(shapePaths[2]);
  61970. shapePaths[1] = shapePaths[2];
  61971. break;
  61972. case BABYLON.Mesh.CAP_END:
  61973. shapePaths[index] = shapePaths[index - 1];
  61974. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61975. break;
  61976. case BABYLON.Mesh.CAP_ALL:
  61977. shapePaths[0] = capPath(shapePaths[2]);
  61978. shapePaths[1] = shapePaths[2];
  61979. shapePaths[index] = shapePaths[index - 1];
  61980. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61981. break;
  61982. default:
  61983. break;
  61984. }
  61985. return shapePaths;
  61986. };
  61987. var path3D;
  61988. var pathArray;
  61989. if (instance) { // instance update
  61990. path3D = (instance.path3D).update(curve);
  61991. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61992. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61993. return instance;
  61994. }
  61995. // extruded shape creation
  61996. path3D = new BABYLON.Path3D(curve);
  61997. var newShapePaths = new Array();
  61998. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61999. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62000. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62001. extrudedGeneric.pathArray = pathArray;
  62002. extrudedGeneric.path3D = path3D;
  62003. extrudedGeneric.cap = cap;
  62004. return extrudedGeneric;
  62005. };
  62006. return MeshBuilder;
  62007. }());
  62008. BABYLON.MeshBuilder = MeshBuilder;
  62009. })(BABYLON || (BABYLON = {}));
  62010. //# sourceMappingURL=babylon.meshBuilder.js.map
  62011. var BABYLON;
  62012. (function (BABYLON) {
  62013. /**
  62014. * Draco compression (https://google.github.io/draco/)
  62015. *
  62016. * This class wraps the Draco module.
  62017. *
  62018. * **Encoder**
  62019. *
  62020. * The encoder is not currently implemented.
  62021. *
  62022. * **Decoder**
  62023. *
  62024. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62025. *
  62026. * To update the configuration, use the following code:
  62027. * ```javascript
  62028. * BABYLON.DracoCompression.Configuration = {
  62029. * decoder: {
  62030. * wasmUrl: "<url to the WebAssembly library>",
  62031. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62032. * fallbackUrl: "<url to the fallback JavaScript library>",
  62033. * }
  62034. * };
  62035. * ```
  62036. *
  62037. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  62038. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62039. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62040. *
  62041. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62042. * ```javascript
  62043. * var dracoCompression = new BABYLON.DracoCompression();
  62044. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62045. * [BABYLON.VertexBuffer.PositionKind]: 0
  62046. * });
  62047. * ```
  62048. *
  62049. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62050. */
  62051. var DracoCompression = /** @class */ (function () {
  62052. /**
  62053. * Constructor
  62054. */
  62055. function DracoCompression() {
  62056. }
  62057. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62058. /**
  62059. * Returns true if the decoder is available.
  62060. */
  62061. get: function () {
  62062. if (typeof DracoDecoderModule !== "undefined") {
  62063. return true;
  62064. }
  62065. var decoder = DracoCompression.Configuration.decoder;
  62066. if (decoder) {
  62067. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62068. return true;
  62069. }
  62070. if (decoder.fallbackUrl) {
  62071. return true;
  62072. }
  62073. }
  62074. return false;
  62075. },
  62076. enumerable: true,
  62077. configurable: true
  62078. });
  62079. /**
  62080. * Stop all async operations and release resources.
  62081. */
  62082. DracoCompression.prototype.dispose = function () {
  62083. };
  62084. /**
  62085. * Decode Draco compressed mesh data to vertex data.
  62086. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62087. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62088. * @returns A promise that resolves with the decoded vertex data
  62089. */
  62090. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62091. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62092. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62093. var module = wrappedModule.module;
  62094. var vertexData = new BABYLON.VertexData();
  62095. var buffer = new module.DecoderBuffer();
  62096. buffer.Init(dataView, dataView.byteLength);
  62097. var decoder = new module.Decoder();
  62098. var geometry;
  62099. var status;
  62100. try {
  62101. var type = decoder.GetEncodedGeometryType(buffer);
  62102. switch (type) {
  62103. case module.TRIANGULAR_MESH:
  62104. geometry = new module.Mesh();
  62105. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62106. break;
  62107. case module.POINT_CLOUD:
  62108. geometry = new module.PointCloud();
  62109. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62110. break;
  62111. default:
  62112. throw new Error("Invalid geometry type " + type);
  62113. }
  62114. if (!status.ok() || !geometry.ptr) {
  62115. throw new Error(status.error_msg());
  62116. }
  62117. var numPoints = geometry.num_points();
  62118. if (type === module.TRIANGULAR_MESH) {
  62119. var numFaces = geometry.num_faces();
  62120. var faceIndices = new module.DracoInt32Array();
  62121. try {
  62122. var indices = new Uint32Array(numFaces * 3);
  62123. for (var i = 0; i < numFaces; i++) {
  62124. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62125. var offset = i * 3;
  62126. indices[offset + 0] = faceIndices.GetValue(0);
  62127. indices[offset + 1] = faceIndices.GetValue(1);
  62128. indices[offset + 2] = faceIndices.GetValue(2);
  62129. }
  62130. vertexData.indices = indices;
  62131. }
  62132. finally {
  62133. module.destroy(faceIndices);
  62134. }
  62135. }
  62136. for (var kind in attributes) {
  62137. var uniqueId = attributes[kind];
  62138. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62139. var dracoData = new module.DracoFloat32Array();
  62140. try {
  62141. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62142. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62143. for (var i = 0; i < babylonData.length; i++) {
  62144. babylonData[i] = dracoData.GetValue(i);
  62145. }
  62146. vertexData.set(babylonData, kind);
  62147. }
  62148. finally {
  62149. module.destroy(dracoData);
  62150. }
  62151. }
  62152. }
  62153. finally {
  62154. if (geometry) {
  62155. module.destroy(geometry);
  62156. }
  62157. module.destroy(decoder);
  62158. module.destroy(buffer);
  62159. }
  62160. return vertexData;
  62161. });
  62162. };
  62163. DracoCompression._GetDecoderModule = function () {
  62164. if (!DracoCompression._DecoderModulePromise) {
  62165. var promise = null;
  62166. var config_1 = {};
  62167. if (typeof DracoDecoderModule !== "undefined") {
  62168. promise = Promise.resolve();
  62169. }
  62170. else {
  62171. var decoder = DracoCompression.Configuration.decoder;
  62172. if (decoder) {
  62173. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62174. promise = Promise.all([
  62175. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62176. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62177. config_1.wasmBinary = data;
  62178. })
  62179. ]);
  62180. }
  62181. else if (decoder.fallbackUrl) {
  62182. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62183. }
  62184. }
  62185. }
  62186. if (!promise) {
  62187. throw new Error("Draco decoder module is not available");
  62188. }
  62189. DracoCompression._DecoderModulePromise = promise.then(function () {
  62190. return new Promise(function (resolve) {
  62191. config_1.onModuleLoaded = function (decoderModule) {
  62192. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62193. resolve({ module: decoderModule });
  62194. };
  62195. DracoDecoderModule(config_1);
  62196. });
  62197. });
  62198. }
  62199. return DracoCompression._DecoderModulePromise;
  62200. };
  62201. DracoCompression._LoadScriptAsync = function (url) {
  62202. return new Promise(function (resolve, reject) {
  62203. BABYLON.Tools.LoadScript(url, function () {
  62204. resolve();
  62205. }, function (message) {
  62206. reject(new Error(message));
  62207. });
  62208. });
  62209. };
  62210. DracoCompression._LoadFileAsync = function (url) {
  62211. return new Promise(function (resolve, reject) {
  62212. BABYLON.Tools.LoadFile(url, function (data) {
  62213. resolve(data);
  62214. }, undefined, undefined, true, function (request, exception) {
  62215. reject(exception);
  62216. });
  62217. });
  62218. };
  62219. /**
  62220. * The configuration. Defaults to the following urls:
  62221. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62222. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62223. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62224. */
  62225. DracoCompression.Configuration = {
  62226. decoder: {
  62227. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62228. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62229. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62230. }
  62231. };
  62232. return DracoCompression;
  62233. }());
  62234. BABYLON.DracoCompression = DracoCompression;
  62235. })(BABYLON || (BABYLON = {}));
  62236. //# sourceMappingURL=babylon.dracoCompression.js.map
  62237. var BABYLON;
  62238. (function (BABYLON) {
  62239. var AudioEngine = /** @class */ (function () {
  62240. function AudioEngine() {
  62241. this._audioContext = null;
  62242. this._audioContextInitialized = false;
  62243. this.canUseWebAudio = false;
  62244. this.WarnedWebAudioUnsupported = false;
  62245. this.unlocked = false;
  62246. this.isMP3supported = false;
  62247. this.isOGGsupported = false;
  62248. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62249. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62250. this.canUseWebAudio = true;
  62251. }
  62252. var audioElem = document.createElement('audio');
  62253. try {
  62254. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62255. this.isMP3supported = true;
  62256. }
  62257. }
  62258. catch (e) {
  62259. // protect error during capability check.
  62260. }
  62261. try {
  62262. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62263. this.isOGGsupported = true;
  62264. }
  62265. }
  62266. catch (e) {
  62267. // protect error during capability check.
  62268. }
  62269. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62270. this._unlockiOSaudio();
  62271. }
  62272. else {
  62273. this.unlocked = true;
  62274. }
  62275. }
  62276. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62277. get: function () {
  62278. if (!this._audioContextInitialized) {
  62279. this._initializeAudioContext();
  62280. }
  62281. return this._audioContext;
  62282. },
  62283. enumerable: true,
  62284. configurable: true
  62285. });
  62286. AudioEngine.prototype._unlockiOSaudio = function () {
  62287. var _this = this;
  62288. var unlockaudio = function () {
  62289. if (!_this.audioContext) {
  62290. return;
  62291. }
  62292. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62293. var source = _this.audioContext.createBufferSource();
  62294. source.buffer = buffer;
  62295. source.connect(_this.audioContext.destination);
  62296. source.start(0);
  62297. setTimeout(function () {
  62298. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62299. _this.unlocked = true;
  62300. window.removeEventListener('touchend', unlockaudio, false);
  62301. if (_this.onAudioUnlocked) {
  62302. _this.onAudioUnlocked();
  62303. }
  62304. }
  62305. }, 0);
  62306. };
  62307. window.addEventListener('touchend', unlockaudio, false);
  62308. };
  62309. AudioEngine.prototype._initializeAudioContext = function () {
  62310. try {
  62311. if (this.canUseWebAudio) {
  62312. this._audioContext = new AudioContext();
  62313. // create a global volume gain node
  62314. this.masterGain = this._audioContext.createGain();
  62315. this.masterGain.gain.value = 1;
  62316. this.masterGain.connect(this._audioContext.destination);
  62317. this._audioContextInitialized = true;
  62318. }
  62319. }
  62320. catch (e) {
  62321. this.canUseWebAudio = false;
  62322. BABYLON.Tools.Error("Web Audio: " + e.message);
  62323. }
  62324. };
  62325. AudioEngine.prototype.dispose = function () {
  62326. if (this.canUseWebAudio && this._audioContextInitialized) {
  62327. if (this._connectedAnalyser && this._audioContext) {
  62328. this._connectedAnalyser.stopDebugCanvas();
  62329. this._connectedAnalyser.dispose();
  62330. this.masterGain.disconnect();
  62331. this.masterGain.connect(this._audioContext.destination);
  62332. this._connectedAnalyser = null;
  62333. }
  62334. this.masterGain.gain.value = 1;
  62335. }
  62336. this.WarnedWebAudioUnsupported = false;
  62337. };
  62338. AudioEngine.prototype.getGlobalVolume = function () {
  62339. if (this.canUseWebAudio && this._audioContextInitialized) {
  62340. return this.masterGain.gain.value;
  62341. }
  62342. else {
  62343. return -1;
  62344. }
  62345. };
  62346. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62347. if (this.canUseWebAudio && this._audioContextInitialized) {
  62348. this.masterGain.gain.value = newVolume;
  62349. }
  62350. };
  62351. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62352. if (this._connectedAnalyser) {
  62353. this._connectedAnalyser.stopDebugCanvas();
  62354. }
  62355. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62356. this._connectedAnalyser = analyser;
  62357. this.masterGain.disconnect();
  62358. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62359. }
  62360. };
  62361. return AudioEngine;
  62362. }());
  62363. BABYLON.AudioEngine = AudioEngine;
  62364. })(BABYLON || (BABYLON = {}));
  62365. //# sourceMappingURL=babylon.audioEngine.js.map
  62366. var BABYLON;
  62367. (function (BABYLON) {
  62368. var Sound = /** @class */ (function () {
  62369. /**
  62370. * Create a sound and attach it to a scene
  62371. * @param name Name of your sound
  62372. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62373. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62374. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62375. */
  62376. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62377. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62378. var _this = this;
  62379. this.autoplay = false;
  62380. this.loop = false;
  62381. this.useCustomAttenuation = false;
  62382. this.spatialSound = false;
  62383. this.refDistance = 1;
  62384. this.rolloffFactor = 1;
  62385. this.maxDistance = 100;
  62386. this.distanceModel = "linear";
  62387. this._panningModel = "equalpower";
  62388. this._playbackRate = 1;
  62389. this._streaming = false;
  62390. this._startTime = 0;
  62391. this._startOffset = 0;
  62392. this._position = BABYLON.Vector3.Zero();
  62393. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62394. this._volume = 1;
  62395. this._isReadyToPlay = false;
  62396. this.isPlaying = false;
  62397. this.isPaused = false;
  62398. this._isDirectional = false;
  62399. // Used if you'd like to create a directional sound.
  62400. // If not set, the sound will be omnidirectional
  62401. this._coneInnerAngle = 360;
  62402. this._coneOuterAngle = 360;
  62403. this._coneOuterGain = 0;
  62404. this._isOutputConnected = false;
  62405. this._urlType = "Unknown";
  62406. this.name = name;
  62407. this._scene = scene;
  62408. this._readyToPlayCallback = readyToPlayCallback;
  62409. // Default custom attenuation function is a linear attenuation
  62410. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62411. if (currentDistance < maxDistance) {
  62412. return currentVolume * (1 - currentDistance / maxDistance);
  62413. }
  62414. else {
  62415. return 0;
  62416. }
  62417. };
  62418. if (options) {
  62419. this.autoplay = options.autoplay || false;
  62420. this.loop = options.loop || false;
  62421. // if volume === 0, we need another way to check this option
  62422. if (options.volume !== undefined) {
  62423. this._volume = options.volume;
  62424. }
  62425. this.spatialSound = options.spatialSound || false;
  62426. this.maxDistance = options.maxDistance || 100;
  62427. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62428. this.rolloffFactor = options.rolloffFactor || 1;
  62429. this.refDistance = options.refDistance || 1;
  62430. this.distanceModel = options.distanceModel || "linear";
  62431. this._playbackRate = options.playbackRate || 1;
  62432. this._streaming = options.streaming || false;
  62433. }
  62434. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62435. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62436. this._soundGain.gain.value = this._volume;
  62437. this._inputAudioNode = this._soundGain;
  62438. this._ouputAudioNode = this._soundGain;
  62439. if (this.spatialSound) {
  62440. this._createSpatialParameters();
  62441. }
  62442. this._scene.mainSoundTrack.AddSound(this);
  62443. var validParameter = true;
  62444. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62445. if (urlOrArrayBuffer) {
  62446. try {
  62447. if (typeof (urlOrArrayBuffer) === "string") {
  62448. this._urlType = "String";
  62449. }
  62450. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62451. this._urlType = "ArrayBuffer";
  62452. }
  62453. else if (urlOrArrayBuffer instanceof MediaStream) {
  62454. this._urlType = "MediaStream";
  62455. }
  62456. else if (Array.isArray(urlOrArrayBuffer)) {
  62457. this._urlType = "Array";
  62458. }
  62459. var urls = [];
  62460. var codecSupportedFound = false;
  62461. switch (this._urlType) {
  62462. case "MediaStream":
  62463. this._streaming = true;
  62464. this._isReadyToPlay = true;
  62465. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62466. if (this.autoplay) {
  62467. this.play();
  62468. }
  62469. if (this._readyToPlayCallback) {
  62470. this._readyToPlayCallback();
  62471. }
  62472. break;
  62473. case "ArrayBuffer":
  62474. if (urlOrArrayBuffer.byteLength > 0) {
  62475. codecSupportedFound = true;
  62476. this._soundLoaded(urlOrArrayBuffer);
  62477. }
  62478. break;
  62479. case "String":
  62480. urls.push(urlOrArrayBuffer);
  62481. case "Array":
  62482. if (urls.length === 0)
  62483. urls = urlOrArrayBuffer;
  62484. // If we found a supported format, we load it immediately and stop the loop
  62485. for (var i = 0; i < urls.length; i++) {
  62486. var url = urls[i];
  62487. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62488. codecSupportedFound = true;
  62489. }
  62490. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62491. codecSupportedFound = true;
  62492. }
  62493. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62494. codecSupportedFound = true;
  62495. }
  62496. if (url.indexOf("blob:") !== -1) {
  62497. codecSupportedFound = true;
  62498. }
  62499. if (codecSupportedFound) {
  62500. // Loading sound using XHR2
  62501. if (!this._streaming) {
  62502. this._scene._loadFile(url, function (data) {
  62503. _this._soundLoaded(data);
  62504. }, undefined, true, true, function (exception) {
  62505. if (exception) {
  62506. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62507. }
  62508. BABYLON.Tools.Error("Sound creation aborted.");
  62509. _this._scene.mainSoundTrack.RemoveSound(_this);
  62510. });
  62511. }
  62512. // Streaming sound using HTML5 Audio tag
  62513. else {
  62514. this._htmlAudioElement = new Audio(url);
  62515. this._htmlAudioElement.controls = false;
  62516. this._htmlAudioElement.loop = this.loop;
  62517. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62518. this._htmlAudioElement.preload = "auto";
  62519. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62520. _this._isReadyToPlay = true;
  62521. if (_this.autoplay) {
  62522. _this.play();
  62523. }
  62524. if (_this._readyToPlayCallback) {
  62525. _this._readyToPlayCallback();
  62526. }
  62527. });
  62528. document.body.appendChild(this._htmlAudioElement);
  62529. }
  62530. break;
  62531. }
  62532. }
  62533. break;
  62534. default:
  62535. validParameter = false;
  62536. break;
  62537. }
  62538. if (!validParameter) {
  62539. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62540. }
  62541. else {
  62542. if (!codecSupportedFound) {
  62543. this._isReadyToPlay = true;
  62544. // Simulating a ready to play event to avoid breaking code path
  62545. if (this._readyToPlayCallback) {
  62546. window.setTimeout(function () {
  62547. if (_this._readyToPlayCallback) {
  62548. _this._readyToPlayCallback();
  62549. }
  62550. }, 1000);
  62551. }
  62552. }
  62553. }
  62554. }
  62555. catch (ex) {
  62556. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62557. this._scene.mainSoundTrack.RemoveSound(this);
  62558. }
  62559. }
  62560. }
  62561. else {
  62562. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62563. this._scene.mainSoundTrack.AddSound(this);
  62564. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62565. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62566. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62567. }
  62568. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62569. if (this._readyToPlayCallback) {
  62570. window.setTimeout(function () {
  62571. if (_this._readyToPlayCallback) {
  62572. _this._readyToPlayCallback();
  62573. }
  62574. }, 1000);
  62575. }
  62576. }
  62577. }
  62578. Sound.prototype.dispose = function () {
  62579. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62580. if (this.isPlaying) {
  62581. this.stop();
  62582. }
  62583. this._isReadyToPlay = false;
  62584. if (this.soundTrackId === -1) {
  62585. this._scene.mainSoundTrack.RemoveSound(this);
  62586. }
  62587. else {
  62588. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62589. }
  62590. if (this._soundGain) {
  62591. this._soundGain.disconnect();
  62592. this._soundGain = null;
  62593. }
  62594. if (this._soundPanner) {
  62595. this._soundPanner.disconnect();
  62596. this._soundPanner = null;
  62597. }
  62598. if (this._soundSource) {
  62599. this._soundSource.disconnect();
  62600. this._soundSource = null;
  62601. }
  62602. this._audioBuffer = null;
  62603. if (this._htmlAudioElement) {
  62604. this._htmlAudioElement.pause();
  62605. this._htmlAudioElement.src = "";
  62606. document.body.removeChild(this._htmlAudioElement);
  62607. }
  62608. if (this._streamingSource) {
  62609. this._streamingSource.disconnect();
  62610. }
  62611. if (this._connectedMesh && this._registerFunc) {
  62612. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62613. this._connectedMesh = null;
  62614. }
  62615. }
  62616. };
  62617. Sound.prototype.isReady = function () {
  62618. return this._isReadyToPlay;
  62619. };
  62620. Sound.prototype._soundLoaded = function (audioData) {
  62621. var _this = this;
  62622. if (!BABYLON.Engine.audioEngine.audioContext) {
  62623. return;
  62624. }
  62625. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62626. _this._audioBuffer = buffer;
  62627. _this._isReadyToPlay = true;
  62628. if (_this.autoplay) {
  62629. _this.play();
  62630. }
  62631. if (_this._readyToPlayCallback) {
  62632. _this._readyToPlayCallback();
  62633. }
  62634. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62635. };
  62636. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62637. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62638. this._audioBuffer = audioBuffer;
  62639. this._isReadyToPlay = true;
  62640. }
  62641. };
  62642. Sound.prototype.updateOptions = function (options) {
  62643. if (options) {
  62644. this.loop = options.loop || this.loop;
  62645. this.maxDistance = options.maxDistance || this.maxDistance;
  62646. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62647. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62648. this.refDistance = options.refDistance || this.refDistance;
  62649. this.distanceModel = options.distanceModel || this.distanceModel;
  62650. this._playbackRate = options.playbackRate || this._playbackRate;
  62651. this._updateSpatialParameters();
  62652. if (this.isPlaying) {
  62653. if (this._streaming && this._htmlAudioElement) {
  62654. this._htmlAudioElement.playbackRate = this._playbackRate;
  62655. }
  62656. else {
  62657. if (this._soundSource) {
  62658. this._soundSource.playbackRate.value = this._playbackRate;
  62659. }
  62660. }
  62661. }
  62662. }
  62663. };
  62664. Sound.prototype._createSpatialParameters = function () {
  62665. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62666. if (this._scene.headphone) {
  62667. this._panningModel = "HRTF";
  62668. }
  62669. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62670. this._updateSpatialParameters();
  62671. this._soundPanner.connect(this._ouputAudioNode);
  62672. this._inputAudioNode = this._soundPanner;
  62673. }
  62674. };
  62675. Sound.prototype._updateSpatialParameters = function () {
  62676. if (this.spatialSound && this._soundPanner) {
  62677. if (this.useCustomAttenuation) {
  62678. // Tricks to disable in a way embedded Web Audio attenuation
  62679. this._soundPanner.distanceModel = "linear";
  62680. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62681. this._soundPanner.refDistance = 1;
  62682. this._soundPanner.rolloffFactor = 1;
  62683. this._soundPanner.panningModel = this._panningModel;
  62684. }
  62685. else {
  62686. this._soundPanner.distanceModel = this.distanceModel;
  62687. this._soundPanner.maxDistance = this.maxDistance;
  62688. this._soundPanner.refDistance = this.refDistance;
  62689. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62690. this._soundPanner.panningModel = this._panningModel;
  62691. }
  62692. }
  62693. };
  62694. Sound.prototype.switchPanningModelToHRTF = function () {
  62695. this._panningModel = "HRTF";
  62696. this._switchPanningModel();
  62697. };
  62698. Sound.prototype.switchPanningModelToEqualPower = function () {
  62699. this._panningModel = "equalpower";
  62700. this._switchPanningModel();
  62701. };
  62702. Sound.prototype._switchPanningModel = function () {
  62703. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62704. this._soundPanner.panningModel = this._panningModel;
  62705. }
  62706. };
  62707. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62708. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62709. if (this._isOutputConnected) {
  62710. this._ouputAudioNode.disconnect();
  62711. }
  62712. this._ouputAudioNode.connect(soundTrackAudioNode);
  62713. this._isOutputConnected = true;
  62714. }
  62715. };
  62716. /**
  62717. * Transform this sound into a directional source
  62718. * @param coneInnerAngle Size of the inner cone in degree
  62719. * @param coneOuterAngle Size of the outer cone in degree
  62720. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62721. */
  62722. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62723. if (coneOuterAngle < coneInnerAngle) {
  62724. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62725. return;
  62726. }
  62727. this._coneInnerAngle = coneInnerAngle;
  62728. this._coneOuterAngle = coneOuterAngle;
  62729. this._coneOuterGain = coneOuterGain;
  62730. this._isDirectional = true;
  62731. if (this.isPlaying && this.loop) {
  62732. this.stop();
  62733. this.play();
  62734. }
  62735. };
  62736. Sound.prototype.setPosition = function (newPosition) {
  62737. this._position = newPosition;
  62738. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62739. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62740. }
  62741. };
  62742. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62743. this._localDirection = newLocalDirection;
  62744. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62745. this._updateDirection();
  62746. }
  62747. };
  62748. Sound.prototype._updateDirection = function () {
  62749. if (!this._connectedMesh || !this._soundPanner) {
  62750. return;
  62751. }
  62752. var mat = this._connectedMesh.getWorldMatrix();
  62753. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62754. direction.normalize();
  62755. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62756. };
  62757. Sound.prototype.updateDistanceFromListener = function () {
  62758. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62759. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62760. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62761. }
  62762. };
  62763. Sound.prototype.setAttenuationFunction = function (callback) {
  62764. this._customAttenuationFunction = callback;
  62765. };
  62766. /**
  62767. * Play the sound
  62768. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62769. * @param offset (optional) Start the sound setting it at a specific time
  62770. */
  62771. Sound.prototype.play = function (time, offset) {
  62772. var _this = this;
  62773. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62774. try {
  62775. if (this._startOffset < 0) {
  62776. time = -this._startOffset;
  62777. this._startOffset = 0;
  62778. }
  62779. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62780. if (!this._soundSource || !this._streamingSource) {
  62781. if (this.spatialSound && this._soundPanner) {
  62782. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62783. if (this._isDirectional) {
  62784. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62785. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62786. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62787. if (this._connectedMesh) {
  62788. this._updateDirection();
  62789. }
  62790. else {
  62791. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62792. }
  62793. }
  62794. }
  62795. }
  62796. if (this._streaming) {
  62797. if (!this._streamingSource) {
  62798. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62799. this._htmlAudioElement.onended = function () { _this._onended(); };
  62800. this._htmlAudioElement.playbackRate = this._playbackRate;
  62801. }
  62802. this._streamingSource.disconnect();
  62803. this._streamingSource.connect(this._inputAudioNode);
  62804. if (this._htmlAudioElement) {
  62805. this._htmlAudioElement.play();
  62806. }
  62807. }
  62808. else {
  62809. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62810. this._soundSource.buffer = this._audioBuffer;
  62811. this._soundSource.connect(this._inputAudioNode);
  62812. this._soundSource.loop = this.loop;
  62813. this._soundSource.playbackRate.value = this._playbackRate;
  62814. this._soundSource.onended = function () { _this._onended(); };
  62815. if (this._soundSource.buffer) {
  62816. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62817. }
  62818. }
  62819. this._startTime = startTime;
  62820. this.isPlaying = true;
  62821. this.isPaused = false;
  62822. }
  62823. catch (ex) {
  62824. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62825. }
  62826. }
  62827. };
  62828. Sound.prototype._onended = function () {
  62829. this.isPlaying = false;
  62830. if (this.onended) {
  62831. this.onended();
  62832. }
  62833. };
  62834. /**
  62835. * Stop the sound
  62836. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62837. */
  62838. Sound.prototype.stop = function (time) {
  62839. if (this.isPlaying) {
  62840. if (this._streaming) {
  62841. if (this._htmlAudioElement) {
  62842. this._htmlAudioElement.pause();
  62843. // Test needed for Firefox or it will generate an Invalid State Error
  62844. if (this._htmlAudioElement.currentTime > 0) {
  62845. this._htmlAudioElement.currentTime = 0;
  62846. }
  62847. }
  62848. else {
  62849. this._streamingSource.disconnect();
  62850. }
  62851. }
  62852. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62853. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62854. this._soundSource.stop(stopTime);
  62855. this._soundSource.onended = function () { };
  62856. if (!this.isPaused) {
  62857. this._startOffset = 0;
  62858. }
  62859. }
  62860. this.isPlaying = false;
  62861. }
  62862. };
  62863. Sound.prototype.pause = function () {
  62864. if (this.isPlaying) {
  62865. this.isPaused = true;
  62866. if (this._streaming) {
  62867. if (this._htmlAudioElement) {
  62868. this._htmlAudioElement.pause();
  62869. }
  62870. else {
  62871. this._streamingSource.disconnect();
  62872. }
  62873. }
  62874. else if (BABYLON.Engine.audioEngine.audioContext) {
  62875. this.stop(0);
  62876. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62877. }
  62878. }
  62879. };
  62880. Sound.prototype.setVolume = function (newVolume, time) {
  62881. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62882. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62883. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62884. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62885. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62886. }
  62887. else {
  62888. this._soundGain.gain.value = newVolume;
  62889. }
  62890. }
  62891. this._volume = newVolume;
  62892. };
  62893. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62894. this._playbackRate = newPlaybackRate;
  62895. if (this.isPlaying) {
  62896. if (this._streaming && this._htmlAudioElement) {
  62897. this._htmlAudioElement.playbackRate = this._playbackRate;
  62898. }
  62899. else if (this._soundSource) {
  62900. this._soundSource.playbackRate.value = this._playbackRate;
  62901. }
  62902. }
  62903. };
  62904. Sound.prototype.getVolume = function () {
  62905. return this._volume;
  62906. };
  62907. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62908. var _this = this;
  62909. if (this._connectedMesh && this._registerFunc) {
  62910. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62911. this._registerFunc = null;
  62912. }
  62913. this._connectedMesh = meshToConnectTo;
  62914. if (!this.spatialSound) {
  62915. this.spatialSound = true;
  62916. this._createSpatialParameters();
  62917. if (this.isPlaying && this.loop) {
  62918. this.stop();
  62919. this.play();
  62920. }
  62921. }
  62922. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62923. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62924. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62925. };
  62926. Sound.prototype.detachFromMesh = function () {
  62927. if (this._connectedMesh && this._registerFunc) {
  62928. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62929. this._registerFunc = null;
  62930. this._connectedMesh = null;
  62931. }
  62932. };
  62933. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62934. if (!node.getBoundingInfo) {
  62935. return;
  62936. }
  62937. var mesh = node;
  62938. var boundingInfo = mesh.getBoundingInfo();
  62939. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62940. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62941. this._updateDirection();
  62942. }
  62943. };
  62944. Sound.prototype.clone = function () {
  62945. var _this = this;
  62946. if (!this._streaming) {
  62947. var setBufferAndRun = function () {
  62948. if (_this._isReadyToPlay) {
  62949. clonedSound._audioBuffer = _this.getAudioBuffer();
  62950. clonedSound._isReadyToPlay = true;
  62951. if (clonedSound.autoplay) {
  62952. clonedSound.play();
  62953. }
  62954. }
  62955. else {
  62956. window.setTimeout(setBufferAndRun, 300);
  62957. }
  62958. };
  62959. var currentOptions = {
  62960. autoplay: this.autoplay, loop: this.loop,
  62961. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62962. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62963. refDistance: this.refDistance, distanceModel: this.distanceModel
  62964. };
  62965. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62966. if (this.useCustomAttenuation) {
  62967. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62968. }
  62969. clonedSound.setPosition(this._position);
  62970. clonedSound.setPlaybackRate(this._playbackRate);
  62971. setBufferAndRun();
  62972. return clonedSound;
  62973. }
  62974. // Can't clone a streaming sound
  62975. else {
  62976. return null;
  62977. }
  62978. };
  62979. Sound.prototype.getAudioBuffer = function () {
  62980. return this._audioBuffer;
  62981. };
  62982. Sound.prototype.serialize = function () {
  62983. var serializationObject = {
  62984. name: this.name,
  62985. url: this.name,
  62986. autoplay: this.autoplay,
  62987. loop: this.loop,
  62988. volume: this._volume,
  62989. spatialSound: this.spatialSound,
  62990. maxDistance: this.maxDistance,
  62991. rolloffFactor: this.rolloffFactor,
  62992. refDistance: this.refDistance,
  62993. distanceModel: this.distanceModel,
  62994. playbackRate: this._playbackRate,
  62995. panningModel: this._panningModel,
  62996. soundTrackId: this.soundTrackId
  62997. };
  62998. if (this.spatialSound) {
  62999. if (this._connectedMesh)
  63000. serializationObject.connectedMeshId = this._connectedMesh.id;
  63001. serializationObject.position = this._position.asArray();
  63002. serializationObject.refDistance = this.refDistance;
  63003. serializationObject.distanceModel = this.distanceModel;
  63004. serializationObject.isDirectional = this._isDirectional;
  63005. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63006. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63007. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63008. serializationObject.coneOuterGain = this._coneOuterGain;
  63009. }
  63010. return serializationObject;
  63011. };
  63012. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63013. var soundName = parsedSound.name;
  63014. var soundUrl;
  63015. if (parsedSound.url) {
  63016. soundUrl = rootUrl + parsedSound.url;
  63017. }
  63018. else {
  63019. soundUrl = rootUrl + soundName;
  63020. }
  63021. var options = {
  63022. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63023. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63024. rolloffFactor: parsedSound.rolloffFactor,
  63025. refDistance: parsedSound.refDistance,
  63026. distanceModel: parsedSound.distanceModel,
  63027. playbackRate: parsedSound.playbackRate
  63028. };
  63029. var newSound;
  63030. if (!sourceSound) {
  63031. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63032. scene._addPendingData(newSound);
  63033. }
  63034. else {
  63035. var setBufferAndRun = function () {
  63036. if (sourceSound._isReadyToPlay) {
  63037. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63038. newSound._isReadyToPlay = true;
  63039. if (newSound.autoplay) {
  63040. newSound.play();
  63041. }
  63042. }
  63043. else {
  63044. window.setTimeout(setBufferAndRun, 300);
  63045. }
  63046. };
  63047. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63048. setBufferAndRun();
  63049. }
  63050. if (parsedSound.position) {
  63051. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63052. newSound.setPosition(soundPosition);
  63053. }
  63054. if (parsedSound.isDirectional) {
  63055. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63056. if (parsedSound.localDirectionToMesh) {
  63057. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63058. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63059. }
  63060. }
  63061. if (parsedSound.connectedMeshId) {
  63062. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63063. if (connectedMesh) {
  63064. newSound.attachToMesh(connectedMesh);
  63065. }
  63066. }
  63067. return newSound;
  63068. };
  63069. return Sound;
  63070. }());
  63071. BABYLON.Sound = Sound;
  63072. })(BABYLON || (BABYLON = {}));
  63073. //# sourceMappingURL=babylon.sound.js.map
  63074. var BABYLON;
  63075. (function (BABYLON) {
  63076. var SoundTrack = /** @class */ (function () {
  63077. function SoundTrack(scene, options) {
  63078. this.id = -1;
  63079. this._isMainTrack = false;
  63080. this._isInitialized = false;
  63081. this._scene = scene;
  63082. this.soundCollection = new Array();
  63083. this._options = options;
  63084. if (!this._isMainTrack) {
  63085. this._scene.soundTracks.push(this);
  63086. this.id = this._scene.soundTracks.length - 1;
  63087. }
  63088. }
  63089. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63090. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63091. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63092. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63093. if (this._options) {
  63094. if (this._options.volume) {
  63095. this._outputAudioNode.gain.value = this._options.volume;
  63096. }
  63097. if (this._options.mainTrack) {
  63098. this._isMainTrack = this._options.mainTrack;
  63099. }
  63100. }
  63101. this._isInitialized = true;
  63102. }
  63103. };
  63104. SoundTrack.prototype.dispose = function () {
  63105. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63106. if (this._connectedAnalyser) {
  63107. this._connectedAnalyser.stopDebugCanvas();
  63108. }
  63109. while (this.soundCollection.length) {
  63110. this.soundCollection[0].dispose();
  63111. }
  63112. if (this._outputAudioNode) {
  63113. this._outputAudioNode.disconnect();
  63114. }
  63115. this._outputAudioNode = null;
  63116. }
  63117. };
  63118. SoundTrack.prototype.AddSound = function (sound) {
  63119. if (!this._isInitialized) {
  63120. this._initializeSoundTrackAudioGraph();
  63121. }
  63122. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63123. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63124. }
  63125. if (sound.soundTrackId) {
  63126. if (sound.soundTrackId === -1) {
  63127. this._scene.mainSoundTrack.RemoveSound(sound);
  63128. }
  63129. else {
  63130. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63131. }
  63132. }
  63133. this.soundCollection.push(sound);
  63134. sound.soundTrackId = this.id;
  63135. };
  63136. SoundTrack.prototype.RemoveSound = function (sound) {
  63137. var index = this.soundCollection.indexOf(sound);
  63138. if (index !== -1) {
  63139. this.soundCollection.splice(index, 1);
  63140. }
  63141. };
  63142. SoundTrack.prototype.setVolume = function (newVolume) {
  63143. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63144. this._outputAudioNode.gain.value = newVolume;
  63145. }
  63146. };
  63147. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63148. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63149. for (var i = 0; i < this.soundCollection.length; i++) {
  63150. this.soundCollection[i].switchPanningModelToHRTF();
  63151. }
  63152. }
  63153. };
  63154. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63155. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63156. for (var i = 0; i < this.soundCollection.length; i++) {
  63157. this.soundCollection[i].switchPanningModelToEqualPower();
  63158. }
  63159. }
  63160. };
  63161. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63162. if (this._connectedAnalyser) {
  63163. this._connectedAnalyser.stopDebugCanvas();
  63164. }
  63165. this._connectedAnalyser = analyser;
  63166. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63167. this._outputAudioNode.disconnect();
  63168. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63169. }
  63170. };
  63171. return SoundTrack;
  63172. }());
  63173. BABYLON.SoundTrack = SoundTrack;
  63174. })(BABYLON || (BABYLON = {}));
  63175. //# sourceMappingURL=babylon.soundtrack.js.map
  63176. var BABYLON;
  63177. (function (BABYLON) {
  63178. /**
  63179. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63180. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63181. */
  63182. var Analyser = /** @class */ (function () {
  63183. /**
  63184. * Creates a new analyser
  63185. * @param scene defines hosting scene
  63186. */
  63187. function Analyser(scene) {
  63188. /**
  63189. * Gets or sets the smoothing
  63190. * @ignorenaming
  63191. */
  63192. this.SMOOTHING = 0.75;
  63193. /**
  63194. * Gets or sets the FFT table size
  63195. * @ignorenaming
  63196. */
  63197. this.FFT_SIZE = 512;
  63198. /**
  63199. * Gets or sets the bar graph amplitude
  63200. * @ignorenaming
  63201. */
  63202. this.BARGRAPHAMPLITUDE = 256;
  63203. /**
  63204. * Gets or sets the position of the debug canvas
  63205. * @ignorenaming
  63206. */
  63207. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63208. /**
  63209. * Gets or sets the debug canvas size
  63210. * @ignorenaming
  63211. */
  63212. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63213. this._scene = scene;
  63214. this._audioEngine = BABYLON.Engine.audioEngine;
  63215. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63216. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63217. this._webAudioAnalyser.minDecibels = -140;
  63218. this._webAudioAnalyser.maxDecibels = 0;
  63219. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63220. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63221. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63222. }
  63223. }
  63224. /**
  63225. * Get the number of data values you will have to play with for the visualization
  63226. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63227. * @returns a number
  63228. */
  63229. Analyser.prototype.getFrequencyBinCount = function () {
  63230. if (this._audioEngine.canUseWebAudio) {
  63231. return this._webAudioAnalyser.frequencyBinCount;
  63232. }
  63233. else {
  63234. return 0;
  63235. }
  63236. };
  63237. /**
  63238. * Gets the current frequency data as a byte array
  63239. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63240. * @returns a Uint8Array
  63241. */
  63242. Analyser.prototype.getByteFrequencyData = function () {
  63243. if (this._audioEngine.canUseWebAudio) {
  63244. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63245. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63246. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63247. }
  63248. return this._byteFreqs;
  63249. };
  63250. /**
  63251. * Gets the current waveform as a byte array
  63252. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63253. * @returns a Uint8Array
  63254. */
  63255. Analyser.prototype.getByteTimeDomainData = function () {
  63256. if (this._audioEngine.canUseWebAudio) {
  63257. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63258. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63259. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63260. }
  63261. return this._byteTime;
  63262. };
  63263. /**
  63264. * Gets the current frequency data as a float array
  63265. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63266. * @returns a Float32Array
  63267. */
  63268. Analyser.prototype.getFloatFrequencyData = function () {
  63269. if (this._audioEngine.canUseWebAudio) {
  63270. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63271. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63272. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63273. }
  63274. return this._floatFreqs;
  63275. };
  63276. /**
  63277. * Renders the debug canvas
  63278. */
  63279. Analyser.prototype.drawDebugCanvas = function () {
  63280. var _this = this;
  63281. if (this._audioEngine.canUseWebAudio) {
  63282. if (!this._debugCanvas) {
  63283. this._debugCanvas = document.createElement("canvas");
  63284. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63285. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63286. this._debugCanvas.style.position = "absolute";
  63287. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63288. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63289. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63290. document.body.appendChild(this._debugCanvas);
  63291. this._registerFunc = function () {
  63292. _this.drawDebugCanvas();
  63293. };
  63294. this._scene.registerBeforeRender(this._registerFunc);
  63295. }
  63296. if (this._registerFunc && this._debugCanvasContext) {
  63297. var workingArray = this.getByteFrequencyData();
  63298. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63299. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63300. // Draw the frequency domain chart.
  63301. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63302. var value = workingArray[i];
  63303. var percent = value / this.BARGRAPHAMPLITUDE;
  63304. var height = this.DEBUGCANVASSIZE.height * percent;
  63305. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63306. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63307. var hue = i / this.getFrequencyBinCount() * 360;
  63308. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63309. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63310. }
  63311. }
  63312. }
  63313. };
  63314. /**
  63315. * Stops rendering the debug canvas and removes it
  63316. */
  63317. Analyser.prototype.stopDebugCanvas = function () {
  63318. if (this._debugCanvas) {
  63319. if (this._registerFunc) {
  63320. this._scene.unregisterBeforeRender(this._registerFunc);
  63321. this._registerFunc = null;
  63322. }
  63323. document.body.removeChild(this._debugCanvas);
  63324. this._debugCanvas = null;
  63325. this._debugCanvasContext = null;
  63326. }
  63327. };
  63328. /**
  63329. * Connects two audio nodes
  63330. * @param inputAudioNode defines first node to connect
  63331. * @param outputAudioNode defines second node to connect
  63332. */
  63333. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63334. if (this._audioEngine.canUseWebAudio) {
  63335. inputAudioNode.connect(this._webAudioAnalyser);
  63336. this._webAudioAnalyser.connect(outputAudioNode);
  63337. }
  63338. };
  63339. /**
  63340. * Releases all associated resources
  63341. */
  63342. Analyser.prototype.dispose = function () {
  63343. if (this._audioEngine.canUseWebAudio) {
  63344. this._webAudioAnalyser.disconnect();
  63345. }
  63346. };
  63347. return Analyser;
  63348. }());
  63349. BABYLON.Analyser = Analyser;
  63350. })(BABYLON || (BABYLON = {}));
  63351. //# sourceMappingURL=babylon.analyser.js.map
  63352. var BABYLON;
  63353. (function (BABYLON) {
  63354. var CubeTexture = /** @class */ (function (_super) {
  63355. __extends(CubeTexture, _super);
  63356. /**
  63357. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63358. * as prefiltered data.
  63359. * @param rootUrl defines the url of the texture or the root name of the six images
  63360. * @param scene defines the scene the texture is attached to
  63361. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63362. * @param noMipmap defines if mipmaps should be created or not
  63363. * @param files defines the six files to load for the different faces
  63364. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63365. * @param onError defines a callback triggered in case of error during load
  63366. * @param format defines the internal format to use for the texture once loaded
  63367. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63368. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63369. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63370. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63371. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63372. * @return the cube texture
  63373. */
  63374. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63375. if (extensions === void 0) { extensions = null; }
  63376. if (noMipmap === void 0) { noMipmap = false; }
  63377. if (files === void 0) { files = null; }
  63378. if (onLoad === void 0) { onLoad = null; }
  63379. if (onError === void 0) { onError = null; }
  63380. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63381. if (prefiltered === void 0) { prefiltered = false; }
  63382. if (forcedExtension === void 0) { forcedExtension = null; }
  63383. if (createPolynomials === void 0) { createPolynomials = false; }
  63384. if (lodScale === void 0) { lodScale = 0.8; }
  63385. if (lodOffset === void 0) { lodOffset = 0; }
  63386. var _this = _super.call(this, scene) || this;
  63387. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63388. /**
  63389. * Gets or sets the center of the bounding box associated with the cube texture
  63390. * It must define where the camera used to render the texture was set
  63391. */
  63392. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63393. _this._rotationY = 0;
  63394. /** @hidden */
  63395. _this._prefiltered = false;
  63396. _this.name = rootUrl;
  63397. _this.url = rootUrl;
  63398. _this._noMipmap = noMipmap;
  63399. _this.hasAlpha = false;
  63400. _this._format = format;
  63401. _this.isCube = true;
  63402. _this._textureMatrix = BABYLON.Matrix.Identity();
  63403. _this._createPolynomials = createPolynomials;
  63404. if (!rootUrl && !files) {
  63405. return _this;
  63406. }
  63407. var lastDot = rootUrl.lastIndexOf(".");
  63408. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63409. var isDDS = (extension === ".dds");
  63410. var isEnv = (extension === ".env");
  63411. if (isEnv) {
  63412. _this.gammaSpace = false;
  63413. _this._prefiltered = false;
  63414. }
  63415. else {
  63416. _this._prefiltered = prefiltered;
  63417. if (prefiltered) {
  63418. _this.gammaSpace = false;
  63419. }
  63420. }
  63421. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63422. if (!files) {
  63423. if (!isEnv && !isDDS && !extensions) {
  63424. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63425. }
  63426. files = [];
  63427. if (extensions) {
  63428. for (var index = 0; index < extensions.length; index++) {
  63429. files.push(rootUrl + extensions[index]);
  63430. }
  63431. }
  63432. }
  63433. _this._files = files;
  63434. if (!_this._texture) {
  63435. if (!scene.useDelayedTextureLoading) {
  63436. if (prefiltered) {
  63437. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63438. }
  63439. else {
  63440. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63441. }
  63442. }
  63443. else {
  63444. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63445. }
  63446. }
  63447. else if (onLoad) {
  63448. if (_this._texture.isReady) {
  63449. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63450. }
  63451. else {
  63452. _this._texture.onLoadedObservable.add(onLoad);
  63453. }
  63454. }
  63455. return _this;
  63456. }
  63457. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63458. get: function () {
  63459. return this._boundingBoxSize;
  63460. },
  63461. /**
  63462. * Gets or sets the size of the bounding box associated with the cube texture
  63463. * When defined, the cubemap will switch to local mode
  63464. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63465. * @example https://www.babylonjs-playground.com/#RNASML
  63466. */
  63467. set: function (value) {
  63468. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63469. return;
  63470. }
  63471. this._boundingBoxSize = value;
  63472. var scene = this.getScene();
  63473. if (scene) {
  63474. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63475. }
  63476. },
  63477. enumerable: true,
  63478. configurable: true
  63479. });
  63480. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63481. /**
  63482. * Gets texture matrix rotation angle around Y axis radians.
  63483. */
  63484. get: function () {
  63485. return this._rotationY;
  63486. },
  63487. /**
  63488. * Sets texture matrix rotation angle around Y axis in radians.
  63489. */
  63490. set: function (value) {
  63491. this._rotationY = value;
  63492. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63493. },
  63494. enumerable: true,
  63495. configurable: true
  63496. });
  63497. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63498. var rootUrlKey = "";
  63499. files.forEach(function (url) { return rootUrlKey += url; });
  63500. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63501. };
  63502. /**
  63503. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63504. * @param url defines the url of the prefiltered texture
  63505. * @param scene defines the scene the texture is attached to
  63506. * @param forcedExtension defines the extension of the file if different from the url
  63507. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63508. * @return the prefiltered texture
  63509. */
  63510. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63511. if (forcedExtension === void 0) { forcedExtension = null; }
  63512. if (createPolynomials === void 0) { createPolynomials = true; }
  63513. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63514. };
  63515. // Methods
  63516. CubeTexture.prototype.delayLoad = function () {
  63517. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63518. return;
  63519. }
  63520. var scene = this.getScene();
  63521. if (!scene) {
  63522. return;
  63523. }
  63524. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63525. this._texture = this._getFromCache(this.url, this._noMipmap);
  63526. if (!this._texture) {
  63527. if (this._prefiltered) {
  63528. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63529. }
  63530. else {
  63531. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63532. }
  63533. }
  63534. };
  63535. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63536. return this._textureMatrix;
  63537. };
  63538. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63539. this._textureMatrix = value;
  63540. };
  63541. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63542. var texture = BABYLON.SerializationHelper.Parse(function () {
  63543. var prefiltered = false;
  63544. if (parsedTexture.prefiltered) {
  63545. prefiltered = parsedTexture.prefiltered;
  63546. }
  63547. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63548. }, parsedTexture, scene);
  63549. // Local Cubemaps
  63550. if (parsedTexture.boundingBoxPosition) {
  63551. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63552. }
  63553. if (parsedTexture.boundingBoxSize) {
  63554. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63555. }
  63556. // Animations
  63557. if (parsedTexture.animations) {
  63558. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63559. var parsedAnimation = parsedTexture.animations[animationIndex];
  63560. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63561. }
  63562. }
  63563. return texture;
  63564. };
  63565. CubeTexture.prototype.clone = function () {
  63566. var _this = this;
  63567. return BABYLON.SerializationHelper.Clone(function () {
  63568. var scene = _this.getScene();
  63569. if (!scene) {
  63570. return _this;
  63571. }
  63572. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63573. }, this);
  63574. };
  63575. __decorate([
  63576. BABYLON.serialize("rotationY")
  63577. ], CubeTexture.prototype, "_rotationY", void 0);
  63578. return CubeTexture;
  63579. }(BABYLON.BaseTexture));
  63580. BABYLON.CubeTexture = CubeTexture;
  63581. })(BABYLON || (BABYLON = {}));
  63582. //# sourceMappingURL=babylon.cubeTexture.js.map
  63583. var BABYLON;
  63584. (function (BABYLON) {
  63585. var RenderTargetTexture = /** @class */ (function (_super) {
  63586. __extends(RenderTargetTexture, _super);
  63587. /**
  63588. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63589. * or used a shadow, depth texture...
  63590. * @param name The friendly name of the texture
  63591. * @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)
  63592. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63593. * @param generateMipMaps True if mip maps need to be generated after render.
  63594. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63595. * @param type The type of the buffer in the RTT (int, half float, float...)
  63596. * @param isCube True if a cube texture needs to be created
  63597. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63598. * @param generateDepthBuffer True to generate a depth buffer
  63599. * @param generateStencilBuffer True to generate a stencil buffer
  63600. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63601. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63602. */
  63603. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63604. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63605. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63606. if (isCube === void 0) { isCube = false; }
  63607. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63608. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63609. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63610. if (isMulti === void 0) { isMulti = false; }
  63611. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63612. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63613. _this.isCube = isCube;
  63614. /**
  63615. * Use this list to define the list of mesh you want to render.
  63616. */
  63617. _this.renderList = new Array();
  63618. _this.renderParticles = true;
  63619. _this.renderSprites = false;
  63620. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63621. _this.ignoreCameraViewport = false;
  63622. // Events
  63623. /**
  63624. * An event triggered when the texture is unbind.
  63625. */
  63626. _this.onBeforeBindObservable = new BABYLON.Observable();
  63627. /**
  63628. * An event triggered when the texture is unbind.
  63629. */
  63630. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63631. /**
  63632. * An event triggered before rendering the texture
  63633. */
  63634. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63635. /**
  63636. * An event triggered after rendering the texture
  63637. */
  63638. _this.onAfterRenderObservable = new BABYLON.Observable();
  63639. /**
  63640. * An event triggered after the texture clear
  63641. */
  63642. _this.onClearObservable = new BABYLON.Observable();
  63643. _this._currentRefreshId = -1;
  63644. _this._refreshRate = 1;
  63645. _this._samples = 1;
  63646. /**
  63647. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63648. * It must define where the camera used to render the texture is set
  63649. */
  63650. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63651. scene = _this.getScene();
  63652. if (!scene) {
  63653. return _this;
  63654. }
  63655. _this._engine = scene.getEngine();
  63656. _this.name = name;
  63657. _this.isRenderTarget = true;
  63658. _this._initialSizeParameter = size;
  63659. _this._processSizeParameter(size);
  63660. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63661. });
  63662. _this._generateMipMaps = generateMipMaps ? true : false;
  63663. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63664. // Rendering groups
  63665. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63666. if (isMulti) {
  63667. return _this;
  63668. }
  63669. _this._renderTargetOptions = {
  63670. generateMipMaps: generateMipMaps,
  63671. type: type,
  63672. format: format,
  63673. samplingMode: samplingMode,
  63674. generateDepthBuffer: generateDepthBuffer,
  63675. generateStencilBuffer: generateStencilBuffer
  63676. };
  63677. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63678. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63679. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63680. }
  63681. if (isCube) {
  63682. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63683. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63684. _this._textureMatrix = BABYLON.Matrix.Identity();
  63685. }
  63686. else {
  63687. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63688. }
  63689. return _this;
  63690. }
  63691. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63692. get: function () {
  63693. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63694. },
  63695. enumerable: true,
  63696. configurable: true
  63697. });
  63698. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63699. get: function () {
  63700. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63701. },
  63702. enumerable: true,
  63703. configurable: true
  63704. });
  63705. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63706. get: function () {
  63707. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63708. },
  63709. enumerable: true,
  63710. configurable: true
  63711. });
  63712. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63713. set: function (callback) {
  63714. if (this._onAfterUnbindObserver) {
  63715. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63716. }
  63717. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63718. },
  63719. enumerable: true,
  63720. configurable: true
  63721. });
  63722. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63723. set: function (callback) {
  63724. if (this._onBeforeRenderObserver) {
  63725. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63726. }
  63727. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63728. },
  63729. enumerable: true,
  63730. configurable: true
  63731. });
  63732. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63733. set: function (callback) {
  63734. if (this._onAfterRenderObserver) {
  63735. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63736. }
  63737. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63738. },
  63739. enumerable: true,
  63740. configurable: true
  63741. });
  63742. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63743. set: function (callback) {
  63744. if (this._onClearObserver) {
  63745. this.onClearObservable.remove(this._onClearObserver);
  63746. }
  63747. this._onClearObserver = this.onClearObservable.add(callback);
  63748. },
  63749. enumerable: true,
  63750. configurable: true
  63751. });
  63752. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63753. get: function () {
  63754. return this._renderTargetOptions;
  63755. },
  63756. enumerable: true,
  63757. configurable: true
  63758. });
  63759. RenderTargetTexture.prototype._onRatioRescale = function () {
  63760. if (this._sizeRatio) {
  63761. this.resize(this._initialSizeParameter);
  63762. }
  63763. };
  63764. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63765. get: function () {
  63766. return this._boundingBoxSize;
  63767. },
  63768. /**
  63769. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63770. * When defined, the cubemap will switch to local mode
  63771. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63772. * @example https://www.babylonjs-playground.com/#RNASML
  63773. */
  63774. set: function (value) {
  63775. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63776. return;
  63777. }
  63778. this._boundingBoxSize = value;
  63779. var scene = this.getScene();
  63780. if (scene) {
  63781. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63782. }
  63783. },
  63784. enumerable: true,
  63785. configurable: true
  63786. });
  63787. /**
  63788. * Creates a depth stencil texture.
  63789. * This is only available in WebGL 2 or with the depth texture extension available.
  63790. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63791. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63792. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63793. */
  63794. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63795. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63796. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63797. if (generateStencil === void 0) { generateStencil = false; }
  63798. if (!this.getScene()) {
  63799. return;
  63800. }
  63801. var engine = this.getScene().getEngine();
  63802. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63803. bilinearFiltering: bilinearFiltering,
  63804. comparisonFunction: comparisonFunction,
  63805. generateStencil: generateStencil,
  63806. isCube: this.isCube
  63807. });
  63808. engine.setFrameBufferDepthStencilTexture(this);
  63809. };
  63810. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63811. if (size.ratio) {
  63812. this._sizeRatio = size.ratio;
  63813. this._size = {
  63814. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63815. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63816. };
  63817. }
  63818. else {
  63819. this._size = size;
  63820. }
  63821. };
  63822. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63823. get: function () {
  63824. return this._samples;
  63825. },
  63826. set: function (value) {
  63827. if (this._samples === value) {
  63828. return;
  63829. }
  63830. var scene = this.getScene();
  63831. if (!scene) {
  63832. return;
  63833. }
  63834. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63835. },
  63836. enumerable: true,
  63837. configurable: true
  63838. });
  63839. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63840. this._currentRefreshId = -1;
  63841. };
  63842. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63843. get: function () {
  63844. return this._refreshRate;
  63845. },
  63846. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63847. set: function (value) {
  63848. this._refreshRate = value;
  63849. this.resetRefreshCounter();
  63850. },
  63851. enumerable: true,
  63852. configurable: true
  63853. });
  63854. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63855. if (!this._postProcessManager) {
  63856. var scene = this.getScene();
  63857. if (!scene) {
  63858. return;
  63859. }
  63860. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63861. this._postProcesses = new Array();
  63862. }
  63863. this._postProcesses.push(postProcess);
  63864. this._postProcesses[0].autoClear = false;
  63865. };
  63866. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63867. if (!this._postProcesses) {
  63868. return;
  63869. }
  63870. if (dispose) {
  63871. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63872. var postProcess = _a[_i];
  63873. postProcess.dispose();
  63874. }
  63875. }
  63876. this._postProcesses = [];
  63877. };
  63878. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63879. if (!this._postProcesses) {
  63880. return;
  63881. }
  63882. var index = this._postProcesses.indexOf(postProcess);
  63883. if (index === -1) {
  63884. return;
  63885. }
  63886. this._postProcesses.splice(index, 1);
  63887. if (this._postProcesses.length > 0) {
  63888. this._postProcesses[0].autoClear = false;
  63889. }
  63890. };
  63891. RenderTargetTexture.prototype._shouldRender = function () {
  63892. if (this._currentRefreshId === -1) { // At least render once
  63893. this._currentRefreshId = 1;
  63894. return true;
  63895. }
  63896. if (this.refreshRate === this._currentRefreshId) {
  63897. this._currentRefreshId = 1;
  63898. return true;
  63899. }
  63900. this._currentRefreshId++;
  63901. return false;
  63902. };
  63903. RenderTargetTexture.prototype.getRenderSize = function () {
  63904. if (this._size.width) {
  63905. return this._size.width;
  63906. }
  63907. return this._size;
  63908. };
  63909. RenderTargetTexture.prototype.getRenderWidth = function () {
  63910. if (this._size.width) {
  63911. return this._size.width;
  63912. }
  63913. return this._size;
  63914. };
  63915. RenderTargetTexture.prototype.getRenderHeight = function () {
  63916. if (this._size.width) {
  63917. return this._size.height;
  63918. }
  63919. return this._size;
  63920. };
  63921. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63922. get: function () {
  63923. return true;
  63924. },
  63925. enumerable: true,
  63926. configurable: true
  63927. });
  63928. RenderTargetTexture.prototype.scale = function (ratio) {
  63929. var newSize = this.getRenderSize() * ratio;
  63930. this.resize(newSize);
  63931. };
  63932. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63933. if (this.isCube) {
  63934. return this._textureMatrix;
  63935. }
  63936. return _super.prototype.getReflectionTextureMatrix.call(this);
  63937. };
  63938. RenderTargetTexture.prototype.resize = function (size) {
  63939. this.releaseInternalTexture();
  63940. var scene = this.getScene();
  63941. if (!scene) {
  63942. return;
  63943. }
  63944. this._processSizeParameter(size);
  63945. if (this.isCube) {
  63946. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63947. }
  63948. else {
  63949. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63950. }
  63951. };
  63952. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63953. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63954. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63955. var scene = this.getScene();
  63956. if (!scene) {
  63957. return;
  63958. }
  63959. var engine = scene.getEngine();
  63960. if (this.useCameraPostProcesses !== undefined) {
  63961. useCameraPostProcess = this.useCameraPostProcesses;
  63962. }
  63963. if (this._waitingRenderList) {
  63964. this.renderList = [];
  63965. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63966. var id = this._waitingRenderList[index];
  63967. var mesh_1 = scene.getMeshByID(id);
  63968. if (mesh_1) {
  63969. this.renderList.push(mesh_1);
  63970. }
  63971. }
  63972. delete this._waitingRenderList;
  63973. }
  63974. // Is predicate defined?
  63975. if (this.renderListPredicate) {
  63976. if (this.renderList) {
  63977. this.renderList.splice(0); // Clear previous renderList
  63978. }
  63979. else {
  63980. this.renderList = [];
  63981. }
  63982. var scene = this.getScene();
  63983. if (!scene) {
  63984. return;
  63985. }
  63986. var sceneMeshes = scene.meshes;
  63987. for (var index = 0; index < sceneMeshes.length; index++) {
  63988. var mesh = sceneMeshes[index];
  63989. if (this.renderListPredicate(mesh)) {
  63990. this.renderList.push(mesh);
  63991. }
  63992. }
  63993. }
  63994. this.onBeforeBindObservable.notifyObservers(this);
  63995. // Set custom projection.
  63996. // Needs to be before binding to prevent changing the aspect ratio.
  63997. var camera;
  63998. if (this.activeCamera) {
  63999. camera = this.activeCamera;
  64000. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64001. if (this.activeCamera !== scene.activeCamera) {
  64002. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64003. }
  64004. }
  64005. else {
  64006. camera = scene.activeCamera;
  64007. if (camera) {
  64008. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64009. }
  64010. }
  64011. // Prepare renderingManager
  64012. this._renderingManager.reset();
  64013. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64014. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64015. var sceneRenderId = scene.getRenderId();
  64016. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64017. var mesh = currentRenderList[meshIndex];
  64018. if (mesh) {
  64019. if (!mesh.isReady(this.refreshRate === 0)) {
  64020. this.resetRefreshCounter();
  64021. continue;
  64022. }
  64023. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64024. var isMasked = void 0;
  64025. if (!this.renderList && camera) {
  64026. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64027. }
  64028. else {
  64029. isMasked = false;
  64030. }
  64031. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64032. mesh._activate(sceneRenderId);
  64033. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64034. var subMesh = mesh.subMeshes[subIndex];
  64035. scene._activeIndices.addCount(subMesh.indexCount, false);
  64036. this._renderingManager.dispatch(subMesh, mesh);
  64037. }
  64038. }
  64039. }
  64040. }
  64041. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64042. var particleSystem = scene.particleSystems[particleIndex];
  64043. var emitter = particleSystem.emitter;
  64044. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64045. continue;
  64046. }
  64047. if (currentRenderList.indexOf(emitter) >= 0) {
  64048. this._renderingManager.dispatchParticles(particleSystem);
  64049. }
  64050. }
  64051. if (this.isCube) {
  64052. for (var face = 0; face < 6; face++) {
  64053. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64054. scene.incrementRenderId();
  64055. scene.resetCachedMaterial();
  64056. }
  64057. }
  64058. else {
  64059. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64060. }
  64061. this.onAfterUnbindObservable.notifyObservers(this);
  64062. if (scene.activeCamera) {
  64063. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64064. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64065. }
  64066. engine.setViewport(scene.activeCamera.viewport);
  64067. }
  64068. scene.resetCachedMaterial();
  64069. };
  64070. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64071. var minimum = 128;
  64072. var x = renderDimension * scale;
  64073. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64074. // Ensure we don't exceed the render dimension (while staying POT)
  64075. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64076. };
  64077. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64078. var _this = this;
  64079. if (!this._texture) {
  64080. return;
  64081. }
  64082. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64083. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64084. });
  64085. };
  64086. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64087. var scene = this.getScene();
  64088. if (!scene) {
  64089. return;
  64090. }
  64091. var engine = scene.getEngine();
  64092. if (!this._texture) {
  64093. return;
  64094. }
  64095. // Bind
  64096. if (this._postProcessManager) {
  64097. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64098. }
  64099. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64100. if (this._texture) {
  64101. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64102. }
  64103. }
  64104. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64105. // Clear
  64106. if (this.onClearObservable.hasObservers()) {
  64107. this.onClearObservable.notifyObservers(engine);
  64108. }
  64109. else {
  64110. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64111. }
  64112. if (!this._doNotChangeAspectRatio) {
  64113. scene.updateTransformMatrix(true);
  64114. }
  64115. // Render
  64116. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64117. if (this._postProcessManager) {
  64118. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64119. }
  64120. else if (useCameraPostProcess) {
  64121. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64122. }
  64123. if (!this._doNotChangeAspectRatio) {
  64124. scene.updateTransformMatrix(true);
  64125. }
  64126. // Dump ?
  64127. if (dumpForDebug) {
  64128. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64129. }
  64130. // Unbind
  64131. if (!this.isCube || faceIndex === 5) {
  64132. if (this.isCube) {
  64133. if (faceIndex === 5) {
  64134. engine.generateMipMapsForCubemap(this._texture);
  64135. }
  64136. }
  64137. this.unbindFrameBuffer(engine, faceIndex);
  64138. }
  64139. else {
  64140. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64141. }
  64142. };
  64143. /**
  64144. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64145. * This allowed control for front to back rendering or reversly depending of the special needs.
  64146. *
  64147. * @param renderingGroupId The rendering group id corresponding to its index
  64148. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64149. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64150. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64151. */
  64152. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64153. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64154. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64155. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64156. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64157. };
  64158. /**
  64159. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64160. *
  64161. * @param renderingGroupId The rendering group id corresponding to its index
  64162. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64163. */
  64164. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64165. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64166. };
  64167. RenderTargetTexture.prototype.clone = function () {
  64168. var textureSize = this.getSize();
  64169. var newTexture = new RenderTargetTexture(this.name, textureSize, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  64170. // Base texture
  64171. newTexture.hasAlpha = this.hasAlpha;
  64172. newTexture.level = this.level;
  64173. // RenderTarget Texture
  64174. newTexture.coordinatesMode = this.coordinatesMode;
  64175. if (this.renderList) {
  64176. newTexture.renderList = this.renderList.slice(0);
  64177. }
  64178. return newTexture;
  64179. };
  64180. RenderTargetTexture.prototype.serialize = function () {
  64181. if (!this.name) {
  64182. return null;
  64183. }
  64184. var serializationObject = _super.prototype.serialize.call(this);
  64185. serializationObject.renderTargetSize = this.getRenderSize();
  64186. serializationObject.renderList = [];
  64187. if (this.renderList) {
  64188. for (var index = 0; index < this.renderList.length; index++) {
  64189. serializationObject.renderList.push(this.renderList[index].id);
  64190. }
  64191. }
  64192. return serializationObject;
  64193. };
  64194. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64195. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64196. var objBuffer = this.getInternalTexture();
  64197. var scene = this.getScene();
  64198. if (objBuffer && scene) {
  64199. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64200. }
  64201. };
  64202. RenderTargetTexture.prototype.dispose = function () {
  64203. if (this._postProcessManager) {
  64204. this._postProcessManager.dispose();
  64205. this._postProcessManager = null;
  64206. }
  64207. this.clearPostProcesses(true);
  64208. if (this._resizeObserver) {
  64209. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64210. this._resizeObserver = null;
  64211. }
  64212. this.renderList = null;
  64213. // Remove from custom render targets
  64214. var scene = this.getScene();
  64215. if (!scene) {
  64216. return;
  64217. }
  64218. var index = scene.customRenderTargets.indexOf(this);
  64219. if (index >= 0) {
  64220. scene.customRenderTargets.splice(index, 1);
  64221. }
  64222. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64223. var camera = _a[_i];
  64224. index = camera.customRenderTargets.indexOf(this);
  64225. if (index >= 0) {
  64226. camera.customRenderTargets.splice(index, 1);
  64227. }
  64228. }
  64229. _super.prototype.dispose.call(this);
  64230. };
  64231. RenderTargetTexture.prototype._rebuild = function () {
  64232. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64233. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64234. }
  64235. if (this._postProcessManager) {
  64236. this._postProcessManager._rebuild();
  64237. }
  64238. };
  64239. /**
  64240. * Clear the info related to rendering groups preventing retention point in material dispose.
  64241. */
  64242. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64243. if (this._renderingManager) {
  64244. this._renderingManager.freeRenderingGroups();
  64245. }
  64246. };
  64247. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64248. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64249. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64250. return RenderTargetTexture;
  64251. }(BABYLON.Texture));
  64252. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64253. })(BABYLON || (BABYLON = {}));
  64254. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64255. var BABYLON;
  64256. (function (BABYLON) {
  64257. ;
  64258. var MultiRenderTarget = /** @class */ (function (_super) {
  64259. __extends(MultiRenderTarget, _super);
  64260. function MultiRenderTarget(name, size, count, scene, options) {
  64261. var _this = this;
  64262. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64263. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64264. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64265. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64266. _this._engine = scene.getEngine();
  64267. if (!_this.isSupported) {
  64268. _this.dispose();
  64269. return;
  64270. }
  64271. var types = [];
  64272. var samplingModes = [];
  64273. for (var i = 0; i < count; i++) {
  64274. if (options && options.types && options.types[i] !== undefined) {
  64275. types.push(options.types[i]);
  64276. }
  64277. else {
  64278. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64279. }
  64280. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64281. samplingModes.push(options.samplingModes[i]);
  64282. }
  64283. else {
  64284. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64285. }
  64286. }
  64287. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64288. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64289. _this._size = size;
  64290. _this._multiRenderTargetOptions = {
  64291. samplingModes: samplingModes,
  64292. generateMipMaps: generateMipMaps,
  64293. generateDepthBuffer: generateDepthBuffer,
  64294. generateStencilBuffer: generateStencilBuffer,
  64295. generateDepthTexture: generateDepthTexture,
  64296. types: types,
  64297. textureCount: count
  64298. };
  64299. _this._createInternalTextures();
  64300. _this._createTextures();
  64301. return _this;
  64302. }
  64303. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64304. get: function () {
  64305. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64306. },
  64307. enumerable: true,
  64308. configurable: true
  64309. });
  64310. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64311. get: function () {
  64312. return this._textures;
  64313. },
  64314. enumerable: true,
  64315. configurable: true
  64316. });
  64317. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64318. get: function () {
  64319. return this._textures[this._textures.length - 1];
  64320. },
  64321. enumerable: true,
  64322. configurable: true
  64323. });
  64324. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64325. set: function (wrap) {
  64326. if (this._textures) {
  64327. for (var i = 0; i < this._textures.length; i++) {
  64328. this._textures[i].wrapU = wrap;
  64329. }
  64330. }
  64331. },
  64332. enumerable: true,
  64333. configurable: true
  64334. });
  64335. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64336. set: function (wrap) {
  64337. if (this._textures) {
  64338. for (var i = 0; i < this._textures.length; i++) {
  64339. this._textures[i].wrapV = wrap;
  64340. }
  64341. }
  64342. },
  64343. enumerable: true,
  64344. configurable: true
  64345. });
  64346. MultiRenderTarget.prototype._rebuild = function () {
  64347. this.releaseInternalTextures();
  64348. this._createInternalTextures();
  64349. for (var i = 0; i < this._internalTextures.length; i++) {
  64350. var texture = this._textures[i];
  64351. texture._texture = this._internalTextures[i];
  64352. }
  64353. // Keeps references to frame buffer and stencil/depth buffer
  64354. this._texture = this._internalTextures[0];
  64355. };
  64356. MultiRenderTarget.prototype._createInternalTextures = function () {
  64357. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64358. };
  64359. MultiRenderTarget.prototype._createTextures = function () {
  64360. this._textures = [];
  64361. for (var i = 0; i < this._internalTextures.length; i++) {
  64362. var texture = new BABYLON.Texture(null, this.getScene());
  64363. texture._texture = this._internalTextures[i];
  64364. this._textures.push(texture);
  64365. }
  64366. // Keeps references to frame buffer and stencil/depth buffer
  64367. this._texture = this._internalTextures[0];
  64368. };
  64369. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64370. get: function () {
  64371. return this._samples;
  64372. },
  64373. set: function (value) {
  64374. if (this._samples === value) {
  64375. return;
  64376. }
  64377. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64378. },
  64379. enumerable: true,
  64380. configurable: true
  64381. });
  64382. MultiRenderTarget.prototype.resize = function (size) {
  64383. this.releaseInternalTextures();
  64384. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64385. this._createInternalTextures();
  64386. };
  64387. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64388. var _this = this;
  64389. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64390. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64391. });
  64392. };
  64393. MultiRenderTarget.prototype.dispose = function () {
  64394. this.releaseInternalTextures();
  64395. _super.prototype.dispose.call(this);
  64396. };
  64397. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64398. if (!this._internalTextures) {
  64399. return;
  64400. }
  64401. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64402. if (this._internalTextures[i] !== undefined) {
  64403. this._internalTextures[i].dispose();
  64404. this._internalTextures.splice(i, 1);
  64405. }
  64406. }
  64407. };
  64408. return MultiRenderTarget;
  64409. }(BABYLON.RenderTargetTexture));
  64410. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64411. })(BABYLON || (BABYLON = {}));
  64412. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64413. var BABYLON;
  64414. (function (BABYLON) {
  64415. var MirrorTexture = /** @class */ (function (_super) {
  64416. __extends(MirrorTexture, _super);
  64417. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64418. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64419. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64420. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64421. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64422. _this.scene = scene;
  64423. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64424. _this._transformMatrix = BABYLON.Matrix.Zero();
  64425. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64426. _this._adaptiveBlurKernel = 0;
  64427. _this._blurKernelX = 0;
  64428. _this._blurKernelY = 0;
  64429. _this._blurRatio = 1.0;
  64430. _this.ignoreCameraViewport = true;
  64431. _this._updateGammaSpace();
  64432. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64433. _this._updateGammaSpace;
  64434. });
  64435. _this.onBeforeRenderObservable.add(function () {
  64436. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64437. _this._savedViewMatrix = scene.getViewMatrix();
  64438. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64439. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64440. scene.clipPlane = _this.mirrorPlane;
  64441. scene.getEngine().cullBackFaces = false;
  64442. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64443. });
  64444. _this.onAfterRenderObservable.add(function () {
  64445. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64446. scene.getEngine().cullBackFaces = true;
  64447. scene._mirroredCameraPosition = null;
  64448. delete scene.clipPlane;
  64449. });
  64450. return _this;
  64451. }
  64452. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64453. get: function () {
  64454. return this._blurRatio;
  64455. },
  64456. set: function (value) {
  64457. if (this._blurRatio === value) {
  64458. return;
  64459. }
  64460. this._blurRatio = value;
  64461. this._preparePostProcesses();
  64462. },
  64463. enumerable: true,
  64464. configurable: true
  64465. });
  64466. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64467. set: function (value) {
  64468. this._adaptiveBlurKernel = value;
  64469. this._autoComputeBlurKernel();
  64470. },
  64471. enumerable: true,
  64472. configurable: true
  64473. });
  64474. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64475. set: function (value) {
  64476. this.blurKernelX = value;
  64477. this.blurKernelY = value;
  64478. },
  64479. enumerable: true,
  64480. configurable: true
  64481. });
  64482. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64483. get: function () {
  64484. return this._blurKernelX;
  64485. },
  64486. set: function (value) {
  64487. if (this._blurKernelX === value) {
  64488. return;
  64489. }
  64490. this._blurKernelX = value;
  64491. this._preparePostProcesses();
  64492. },
  64493. enumerable: true,
  64494. configurable: true
  64495. });
  64496. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64497. get: function () {
  64498. return this._blurKernelY;
  64499. },
  64500. set: function (value) {
  64501. if (this._blurKernelY === value) {
  64502. return;
  64503. }
  64504. this._blurKernelY = value;
  64505. this._preparePostProcesses();
  64506. },
  64507. enumerable: true,
  64508. configurable: true
  64509. });
  64510. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64511. var engine = this.getScene().getEngine();
  64512. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64513. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64514. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64515. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64516. };
  64517. MirrorTexture.prototype._onRatioRescale = function () {
  64518. if (this._sizeRatio) {
  64519. this.resize(this._initialSizeParameter);
  64520. if (!this._adaptiveBlurKernel) {
  64521. this._preparePostProcesses();
  64522. }
  64523. }
  64524. if (this._adaptiveBlurKernel) {
  64525. this._autoComputeBlurKernel();
  64526. }
  64527. };
  64528. MirrorTexture.prototype._updateGammaSpace = function () {
  64529. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64530. };
  64531. MirrorTexture.prototype._preparePostProcesses = function () {
  64532. this.clearPostProcesses(true);
  64533. if (this._blurKernelX && this._blurKernelY) {
  64534. var engine = this.getScene().getEngine();
  64535. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64536. 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);
  64537. this._blurX.autoClear = false;
  64538. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64539. this._blurX.inputTexture = this._texture;
  64540. }
  64541. else {
  64542. this._blurX.alwaysForcePOT = true;
  64543. }
  64544. 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);
  64545. this._blurY.autoClear = false;
  64546. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64547. this.addPostProcess(this._blurX);
  64548. this.addPostProcess(this._blurY);
  64549. }
  64550. else {
  64551. if (this._blurY) {
  64552. this.removePostProcess(this._blurY);
  64553. this._blurY.dispose();
  64554. this._blurY = null;
  64555. }
  64556. if (this._blurX) {
  64557. this.removePostProcess(this._blurX);
  64558. this._blurX.dispose();
  64559. this._blurX = null;
  64560. }
  64561. }
  64562. };
  64563. MirrorTexture.prototype.clone = function () {
  64564. var scene = this.getScene();
  64565. if (!scene) {
  64566. return this;
  64567. }
  64568. var textureSize = this.getSize();
  64569. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64570. // Base texture
  64571. newTexture.hasAlpha = this.hasAlpha;
  64572. newTexture.level = this.level;
  64573. // Mirror Texture
  64574. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64575. if (this.renderList) {
  64576. newTexture.renderList = this.renderList.slice(0);
  64577. }
  64578. return newTexture;
  64579. };
  64580. MirrorTexture.prototype.serialize = function () {
  64581. if (!this.name) {
  64582. return null;
  64583. }
  64584. var serializationObject = _super.prototype.serialize.call(this);
  64585. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64586. return serializationObject;
  64587. };
  64588. MirrorTexture.prototype.dispose = function () {
  64589. _super.prototype.dispose.call(this);
  64590. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64591. };
  64592. return MirrorTexture;
  64593. }(BABYLON.RenderTargetTexture));
  64594. BABYLON.MirrorTexture = MirrorTexture;
  64595. })(BABYLON || (BABYLON = {}));
  64596. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64597. var BABYLON;
  64598. (function (BABYLON) {
  64599. /**
  64600. * Creates a refraction texture used by refraction channel of the standard material.
  64601. * @param name the texture name
  64602. * @param size size of the underlying texture
  64603. * @param scene root scene
  64604. */
  64605. var RefractionTexture = /** @class */ (function (_super) {
  64606. __extends(RefractionTexture, _super);
  64607. function RefractionTexture(name, size, scene, generateMipMaps) {
  64608. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64609. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64610. _this.depth = 2.0;
  64611. _this.onBeforeRenderObservable.add(function () {
  64612. scene.clipPlane = _this.refractionPlane;
  64613. });
  64614. _this.onAfterRenderObservable.add(function () {
  64615. delete scene.clipPlane;
  64616. });
  64617. return _this;
  64618. }
  64619. RefractionTexture.prototype.clone = function () {
  64620. var scene = this.getScene();
  64621. if (!scene) {
  64622. return this;
  64623. }
  64624. var textureSize = this.getSize();
  64625. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64626. // Base texture
  64627. newTexture.hasAlpha = this.hasAlpha;
  64628. newTexture.level = this.level;
  64629. // Refraction Texture
  64630. newTexture.refractionPlane = this.refractionPlane.clone();
  64631. if (this.renderList) {
  64632. newTexture.renderList = this.renderList.slice(0);
  64633. }
  64634. newTexture.depth = this.depth;
  64635. return newTexture;
  64636. };
  64637. RefractionTexture.prototype.serialize = function () {
  64638. if (!this.name) {
  64639. return null;
  64640. }
  64641. var serializationObject = _super.prototype.serialize.call(this);
  64642. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64643. serializationObject.depth = this.depth;
  64644. return serializationObject;
  64645. };
  64646. return RefractionTexture;
  64647. }(BABYLON.RenderTargetTexture));
  64648. BABYLON.RefractionTexture = RefractionTexture;
  64649. })(BABYLON || (BABYLON = {}));
  64650. //# sourceMappingURL=babylon.refractionTexture.js.map
  64651. var BABYLON;
  64652. (function (BABYLON) {
  64653. /**
  64654. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64655. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64656. */
  64657. var DynamicTexture = /** @class */ (function (_super) {
  64658. __extends(DynamicTexture, _super);
  64659. /**
  64660. * Creates a {BABYLON.DynamicTexture}
  64661. * @param name defines the name of the texture
  64662. * @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
  64663. * @param scene defines the scene where you want the texture
  64664. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64665. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64666. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64667. */
  64668. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64669. if (scene === void 0) { scene = null; }
  64670. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64671. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64672. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64673. _this.name = name;
  64674. _this._engine = _this.getScene().getEngine();
  64675. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64676. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64677. _this._generateMipMaps = generateMipMaps;
  64678. if (options.getContext) {
  64679. _this._canvas = options;
  64680. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64681. }
  64682. else {
  64683. _this._canvas = document.createElement("canvas");
  64684. if (options.width || options.width === 0) {
  64685. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64686. }
  64687. else {
  64688. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64689. }
  64690. }
  64691. var textureSize = _this.getSize();
  64692. _this._canvas.width = textureSize.width;
  64693. _this._canvas.height = textureSize.height;
  64694. _this._context = _this._canvas.getContext("2d");
  64695. return _this;
  64696. }
  64697. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64698. /**
  64699. * Gets the current state of canRescale
  64700. */
  64701. get: function () {
  64702. return true;
  64703. },
  64704. enumerable: true,
  64705. configurable: true
  64706. });
  64707. DynamicTexture.prototype._recreate = function (textureSize) {
  64708. this._canvas.width = textureSize.width;
  64709. this._canvas.height = textureSize.height;
  64710. this.releaseInternalTexture();
  64711. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64712. };
  64713. /**
  64714. * Scales the texture
  64715. * @param ratio the scale factor to apply to both width and height
  64716. */
  64717. DynamicTexture.prototype.scale = function (ratio) {
  64718. var textureSize = this.getSize();
  64719. textureSize.width *= ratio;
  64720. textureSize.height *= ratio;
  64721. this._recreate(textureSize);
  64722. };
  64723. /**
  64724. * Resizes the texture
  64725. * @param width the new width
  64726. * @param height the new height
  64727. */
  64728. DynamicTexture.prototype.scaleTo = function (width, height) {
  64729. var textureSize = this.getSize();
  64730. textureSize.width = width;
  64731. textureSize.height = height;
  64732. this._recreate(textureSize);
  64733. };
  64734. /**
  64735. * Gets the context of the canvas used by the texture
  64736. * @returns the canvas context of the dynamic texture
  64737. */
  64738. DynamicTexture.prototype.getContext = function () {
  64739. return this._context;
  64740. };
  64741. /**
  64742. * Clears the texture
  64743. */
  64744. DynamicTexture.prototype.clear = function () {
  64745. var size = this.getSize();
  64746. this._context.fillRect(0, 0, size.width, size.height);
  64747. };
  64748. /**
  64749. * Updates the texture
  64750. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64751. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64752. */
  64753. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64754. if (premulAlpha === void 0) { premulAlpha = false; }
  64755. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64756. };
  64757. /**
  64758. * Draws text onto the texture
  64759. * @param text defines the text to be drawn
  64760. * @param x defines the placement of the text from the left
  64761. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64762. * @param font defines the font to be used with font-style, font-size, font-name
  64763. * @param color defines the color used for the text
  64764. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64765. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64766. * @param update defines whether texture is immediately update (default is true)
  64767. */
  64768. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64769. if (update === void 0) { update = true; }
  64770. var size = this.getSize();
  64771. if (clearColor) {
  64772. this._context.fillStyle = clearColor;
  64773. this._context.fillRect(0, 0, size.width, size.height);
  64774. }
  64775. this._context.font = font;
  64776. if (x === null || x === undefined) {
  64777. var textSize = this._context.measureText(text);
  64778. x = (size.width - textSize.width) / 2;
  64779. }
  64780. if (y === null || y === undefined) {
  64781. var fontSize = parseInt((font.replace(/\D/g, '')));
  64782. y = (size.height / 2) + (fontSize / 3.65);
  64783. }
  64784. this._context.fillStyle = color;
  64785. this._context.fillText(text, x, y);
  64786. if (update) {
  64787. this.update(invertY);
  64788. }
  64789. };
  64790. /**
  64791. * Clones the texture
  64792. * @returns the clone of the texture.
  64793. */
  64794. DynamicTexture.prototype.clone = function () {
  64795. var scene = this.getScene();
  64796. if (!scene) {
  64797. return this;
  64798. }
  64799. var textureSize = this.getSize();
  64800. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64801. // Base texture
  64802. newTexture.hasAlpha = this.hasAlpha;
  64803. newTexture.level = this.level;
  64804. // Dynamic Texture
  64805. newTexture.wrapU = this.wrapU;
  64806. newTexture.wrapV = this.wrapV;
  64807. return newTexture;
  64808. };
  64809. /** @hidden */
  64810. DynamicTexture.prototype._rebuild = function () {
  64811. this.update();
  64812. };
  64813. return DynamicTexture;
  64814. }(BABYLON.Texture));
  64815. BABYLON.DynamicTexture = DynamicTexture;
  64816. })(BABYLON || (BABYLON = {}));
  64817. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64818. var BABYLON;
  64819. (function (BABYLON) {
  64820. var VideoTexture = /** @class */ (function (_super) {
  64821. __extends(VideoTexture, _super);
  64822. /**
  64823. * Creates a video texture.
  64824. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64825. * @param {string | null} name optional name, will detect from video source, if not defined
  64826. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64827. * @param {BABYLON.Scene} scene is obviously the current scene.
  64828. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64829. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64830. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64831. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64832. */
  64833. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64834. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64835. if (invertY === void 0) { invertY = false; }
  64836. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64837. if (settings === void 0) { settings = {
  64838. autoPlay: true,
  64839. loop: true,
  64840. autoUpdateTexture: true,
  64841. }; }
  64842. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64843. _this._onUserActionRequestedObservable = null;
  64844. _this._stillImageCaptured = false;
  64845. _this._createInternalTexture = function () {
  64846. if (_this._texture != null) {
  64847. return;
  64848. }
  64849. if (!_this._engine.needPOTTextures ||
  64850. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64851. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64852. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64853. }
  64854. else {
  64855. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64856. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64857. _this._generateMipMaps = false;
  64858. }
  64859. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64860. if (!_this.video.autoplay) {
  64861. var oldHandler_1 = _this.video.onplaying;
  64862. var error_1 = false;
  64863. _this.video.onplaying = function () {
  64864. _this.video.onplaying = oldHandler_1;
  64865. _this._texture.isReady = true;
  64866. _this._updateInternalTexture();
  64867. if (!error_1) {
  64868. _this.video.pause();
  64869. }
  64870. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64871. _this.onLoadObservable.notifyObservers(_this);
  64872. }
  64873. };
  64874. var playing = _this.video.play();
  64875. if (playing) {
  64876. playing.then(function () {
  64877. // Everything is good.
  64878. })
  64879. .catch(function () {
  64880. error_1 = true;
  64881. // On Chrome for instance, new policies might prevent playing without user interaction.
  64882. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64883. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64884. }
  64885. });
  64886. }
  64887. else {
  64888. _this.video.onplaying = oldHandler_1;
  64889. _this._texture.isReady = true;
  64890. _this._updateInternalTexture();
  64891. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64892. _this.onLoadObservable.notifyObservers(_this);
  64893. }
  64894. }
  64895. }
  64896. else {
  64897. _this._texture.isReady = true;
  64898. _this._updateInternalTexture();
  64899. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64900. _this.onLoadObservable.notifyObservers(_this);
  64901. }
  64902. }
  64903. };
  64904. _this.reset = function () {
  64905. if (_this._texture == null) {
  64906. return;
  64907. }
  64908. _this._texture.dispose();
  64909. _this._texture = null;
  64910. };
  64911. _this._updateInternalTexture = function (e) {
  64912. if (_this._texture == null || !_this._texture.isReady) {
  64913. return;
  64914. }
  64915. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64916. return;
  64917. }
  64918. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64919. };
  64920. _this._engine = _this.getScene().getEngine();
  64921. _this._generateMipMaps = generateMipMaps;
  64922. _this._samplingMode = samplingMode;
  64923. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64924. _this.name = name || _this._getName(src);
  64925. _this.video = _this._getVideo(src);
  64926. if (settings.poster) {
  64927. _this.video.poster = settings.poster;
  64928. }
  64929. if (settings.autoPlay !== undefined) {
  64930. _this.video.autoplay = settings.autoPlay;
  64931. }
  64932. if (settings.loop !== undefined) {
  64933. _this.video.loop = settings.loop;
  64934. }
  64935. _this.video.setAttribute("playsinline", "");
  64936. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64937. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64938. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64939. _this.video.addEventListener("emptied", _this.reset);
  64940. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64941. _this._createInternalTexture();
  64942. }
  64943. return _this;
  64944. }
  64945. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64946. get: function () {
  64947. if (!this._onUserActionRequestedObservable) {
  64948. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64949. }
  64950. return this._onUserActionRequestedObservable;
  64951. },
  64952. enumerable: true,
  64953. configurable: true
  64954. });
  64955. VideoTexture.prototype._getName = function (src) {
  64956. if (src instanceof HTMLVideoElement) {
  64957. return src.currentSrc;
  64958. }
  64959. if (typeof src === "object") {
  64960. return src.toString();
  64961. }
  64962. return src;
  64963. };
  64964. ;
  64965. VideoTexture.prototype._getVideo = function (src) {
  64966. if (src instanceof HTMLVideoElement) {
  64967. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64968. return src;
  64969. }
  64970. var video = document.createElement("video");
  64971. if (typeof src === "string") {
  64972. BABYLON.Tools.SetCorsBehavior(src, video);
  64973. video.src = src;
  64974. }
  64975. else {
  64976. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64977. src.forEach(function (url) {
  64978. var source = document.createElement("source");
  64979. source.src = url;
  64980. video.appendChild(source);
  64981. });
  64982. }
  64983. return video;
  64984. };
  64985. ;
  64986. /**
  64987. * Internal method to initiate `update`.
  64988. */
  64989. VideoTexture.prototype._rebuild = function () {
  64990. this.update();
  64991. };
  64992. /**
  64993. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64994. */
  64995. VideoTexture.prototype.update = function () {
  64996. if (!this.autoUpdateTexture) {
  64997. // Expecting user to call `updateTexture` manually
  64998. return;
  64999. }
  65000. this.updateTexture(true);
  65001. };
  65002. /**
  65003. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65004. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65005. */
  65006. VideoTexture.prototype.updateTexture = function (isVisible) {
  65007. if (!isVisible) {
  65008. return;
  65009. }
  65010. if (this.video.paused && this._stillImageCaptured) {
  65011. return;
  65012. }
  65013. this._stillImageCaptured = true;
  65014. this._updateInternalTexture();
  65015. };
  65016. /**
  65017. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65018. * @param url New url.
  65019. */
  65020. VideoTexture.prototype.updateURL = function (url) {
  65021. this.video.src = url;
  65022. };
  65023. VideoTexture.prototype.dispose = function () {
  65024. _super.prototype.dispose.call(this);
  65025. if (this._onUserActionRequestedObservable) {
  65026. this._onUserActionRequestedObservable.clear();
  65027. this._onUserActionRequestedObservable = null;
  65028. }
  65029. this.video.removeEventListener("canplay", this._createInternalTexture);
  65030. this.video.removeEventListener("paused", this._updateInternalTexture);
  65031. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65032. this.video.removeEventListener("emptied", this.reset);
  65033. this.video.pause();
  65034. };
  65035. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65036. var video = document.createElement("video");
  65037. video.setAttribute('autoplay', '');
  65038. video.setAttribute('muted', '');
  65039. video.setAttribute('playsinline', '');
  65040. var constraintsDeviceId;
  65041. if (constraints && constraints.deviceId) {
  65042. constraintsDeviceId = {
  65043. exact: constraints.deviceId,
  65044. };
  65045. }
  65046. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65047. if (navigator.mediaDevices) {
  65048. navigator.mediaDevices.getUserMedia({ video: constraints })
  65049. .then(function (stream) {
  65050. if (video.mozSrcObject !== undefined) {
  65051. // hack for Firefox < 19
  65052. video.mozSrcObject = stream;
  65053. }
  65054. else {
  65055. video.srcObject = stream;
  65056. }
  65057. var onPlaying = function () {
  65058. if (onReady) {
  65059. onReady(new VideoTexture("video", video, scene, true, true));
  65060. }
  65061. video.removeEventListener("playing", onPlaying);
  65062. };
  65063. video.addEventListener("playing", onPlaying);
  65064. video.play();
  65065. })
  65066. .catch(function (err) {
  65067. BABYLON.Tools.Error(err.name);
  65068. });
  65069. }
  65070. else {
  65071. navigator.getUserMedia =
  65072. navigator.getUserMedia ||
  65073. navigator.webkitGetUserMedia ||
  65074. navigator.mozGetUserMedia ||
  65075. navigator.msGetUserMedia;
  65076. if (navigator.getUserMedia) {
  65077. navigator.getUserMedia({
  65078. video: {
  65079. deviceId: constraintsDeviceId,
  65080. width: {
  65081. min: (constraints && constraints.minWidth) || 256,
  65082. max: (constraints && constraints.maxWidth) || 640,
  65083. },
  65084. height: {
  65085. min: (constraints && constraints.minHeight) || 256,
  65086. max: (constraints && constraints.maxHeight) || 480,
  65087. },
  65088. },
  65089. }, function (stream) {
  65090. if (video.mozSrcObject !== undefined) {
  65091. // hack for Firefox < 19
  65092. video.mozSrcObject = stream;
  65093. }
  65094. else {
  65095. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65096. }
  65097. video.play();
  65098. if (onReady) {
  65099. onReady(new VideoTexture("video", video, scene, true, true));
  65100. }
  65101. }, function (e) {
  65102. BABYLON.Tools.Error(e.name);
  65103. });
  65104. }
  65105. }
  65106. };
  65107. return VideoTexture;
  65108. }(BABYLON.Texture));
  65109. BABYLON.VideoTexture = VideoTexture;
  65110. })(BABYLON || (BABYLON = {}));
  65111. //# sourceMappingURL=babylon.videoTexture.js.map
  65112. var BABYLON;
  65113. (function (BABYLON) {
  65114. var RawTexture = /** @class */ (function (_super) {
  65115. __extends(RawTexture, _super);
  65116. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65117. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65118. if (invertY === void 0) { invertY = false; }
  65119. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65120. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65121. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65122. _this.format = format;
  65123. _this._engine = scene.getEngine();
  65124. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65125. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65126. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65127. return _this;
  65128. }
  65129. RawTexture.prototype.update = function (data) {
  65130. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65131. };
  65132. // Statics
  65133. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65134. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65135. if (invertY === void 0) { invertY = false; }
  65136. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65137. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65138. };
  65139. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65140. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65141. if (invertY === void 0) { invertY = false; }
  65142. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65143. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65144. };
  65145. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65146. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65147. if (invertY === void 0) { invertY = false; }
  65148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65149. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65150. };
  65151. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65152. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65153. if (invertY === void 0) { invertY = false; }
  65154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65155. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65156. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65157. };
  65158. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65159. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65160. if (invertY === void 0) { invertY = false; }
  65161. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65162. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65163. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65164. };
  65165. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65166. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65167. if (invertY === void 0) { invertY = false; }
  65168. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65169. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65170. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  65171. };
  65172. return RawTexture;
  65173. }(BABYLON.Texture));
  65174. BABYLON.RawTexture = RawTexture;
  65175. })(BABYLON || (BABYLON = {}));
  65176. //# sourceMappingURL=babylon.rawTexture.js.map
  65177. var BABYLON;
  65178. (function (BABYLON) {
  65179. /**
  65180. * Class used to store 3D textures containing user data
  65181. */
  65182. var RawTexture3D = /** @class */ (function (_super) {
  65183. __extends(RawTexture3D, _super);
  65184. /**
  65185. * Create a new RawTexture3D
  65186. * @param data defines the data of the texture
  65187. * @param width defines the width of the texture
  65188. * @param height defines the height of the texture
  65189. * @param depth defines the depth of the texture
  65190. * @param format defines the texture format to use
  65191. * @param scene defines the hosting scene
  65192. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65193. * @param invertY defines if texture must be stored with Y axis inverted
  65194. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65195. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65196. */
  65197. function RawTexture3D(data, width, height, depth,
  65198. /** Gets or sets the texture format to use */
  65199. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65200. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65201. if (invertY === void 0) { invertY = false; }
  65202. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65203. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65204. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65205. _this.format = format;
  65206. _this._engine = scene.getEngine();
  65207. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65208. _this.is3D = true;
  65209. return _this;
  65210. }
  65211. /**
  65212. * Update the texture with new data
  65213. * @param data defines the data to store in the texture
  65214. */
  65215. RawTexture3D.prototype.update = function (data) {
  65216. if (!this._texture) {
  65217. return;
  65218. }
  65219. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65220. };
  65221. return RawTexture3D;
  65222. }(BABYLON.Texture));
  65223. BABYLON.RawTexture3D = RawTexture3D;
  65224. })(BABYLON || (BABYLON = {}));
  65225. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65226. var BABYLON;
  65227. (function (BABYLON) {
  65228. /**
  65229. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65230. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65231. */
  65232. var PostProcessManager = /** @class */ (function () {
  65233. /**
  65234. * Creates a new instance PostProcess
  65235. * @param scene The scene that the post process is associated with.
  65236. */
  65237. function PostProcessManager(scene) {
  65238. this._vertexBuffers = {};
  65239. this._scene = scene;
  65240. }
  65241. PostProcessManager.prototype._prepareBuffers = function () {
  65242. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65243. return;
  65244. }
  65245. // VBO
  65246. var vertices = [];
  65247. vertices.push(1, 1);
  65248. vertices.push(-1, 1);
  65249. vertices.push(-1, -1);
  65250. vertices.push(1, -1);
  65251. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65252. this._buildIndexBuffer();
  65253. };
  65254. PostProcessManager.prototype._buildIndexBuffer = function () {
  65255. // Indices
  65256. var indices = [];
  65257. indices.push(0);
  65258. indices.push(1);
  65259. indices.push(2);
  65260. indices.push(0);
  65261. indices.push(2);
  65262. indices.push(3);
  65263. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65264. };
  65265. /**
  65266. * Rebuilds the vertex buffers of the manager.
  65267. */
  65268. PostProcessManager.prototype._rebuild = function () {
  65269. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65270. if (!vb) {
  65271. return;
  65272. }
  65273. vb._rebuild();
  65274. this._buildIndexBuffer();
  65275. };
  65276. // Methods
  65277. /**
  65278. * Prepares a frame to be run through a post process.
  65279. * @param sourceTexture The input texture to the post procesess. (default: null)
  65280. * @param postProcesses An array of post processes to be run. (default: null)
  65281. * @returns True if the post processes were able to be run.
  65282. */
  65283. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65284. if (sourceTexture === void 0) { sourceTexture = null; }
  65285. if (postProcesses === void 0) { postProcesses = null; }
  65286. var camera = this._scene.activeCamera;
  65287. if (!camera) {
  65288. return false;
  65289. }
  65290. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65291. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65292. return false;
  65293. }
  65294. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65295. return true;
  65296. };
  65297. /**
  65298. * Manually render a set of post processes to a texture.
  65299. * @param postProcesses An array of post processes to be run.
  65300. * @param targetTexture The target texture to render to.
  65301. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65302. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65303. * @param lodLevel defines which lod of the texture to render to
  65304. */
  65305. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65306. if (targetTexture === void 0) { targetTexture = null; }
  65307. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65308. if (faceIndex === void 0) { faceIndex = 0; }
  65309. if (lodLevel === void 0) { lodLevel = 0; }
  65310. var engine = this._scene.getEngine();
  65311. for (var index = 0; index < postProcesses.length; index++) {
  65312. if (index < postProcesses.length - 1) {
  65313. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65314. }
  65315. else {
  65316. if (targetTexture) {
  65317. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65318. }
  65319. else {
  65320. engine.restoreDefaultFramebuffer();
  65321. }
  65322. }
  65323. var pp = postProcesses[index];
  65324. var effect = pp.apply();
  65325. if (effect) {
  65326. pp.onBeforeRenderObservable.notifyObservers(effect);
  65327. // VBOs
  65328. this._prepareBuffers();
  65329. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65330. // Draw order
  65331. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65332. pp.onAfterRenderObservable.notifyObservers(effect);
  65333. }
  65334. }
  65335. // Restore depth buffer
  65336. engine.setDepthBuffer(true);
  65337. engine.setDepthWrite(true);
  65338. };
  65339. /**
  65340. * Finalize the result of the output of the postprocesses.
  65341. * @param doNotPresent If true the result will not be displayed to the screen.
  65342. * @param targetTexture The target texture to render to.
  65343. * @param faceIndex The index of the face to bind the target texture to.
  65344. * @param postProcesses The array of post processes to render.
  65345. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65346. */
  65347. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65348. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65349. var camera = this._scene.activeCamera;
  65350. if (!camera) {
  65351. return;
  65352. }
  65353. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65354. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65355. return;
  65356. }
  65357. var engine = this._scene.getEngine();
  65358. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65359. var pp = postProcesses[index];
  65360. if (index < len - 1) {
  65361. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65362. }
  65363. else {
  65364. if (targetTexture) {
  65365. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65366. pp._outputTexture = targetTexture;
  65367. }
  65368. else {
  65369. engine.restoreDefaultFramebuffer();
  65370. pp._outputTexture = null;
  65371. }
  65372. }
  65373. if (doNotPresent) {
  65374. break;
  65375. }
  65376. var effect = pp.apply();
  65377. if (effect) {
  65378. pp.onBeforeRenderObservable.notifyObservers(effect);
  65379. // VBOs
  65380. this._prepareBuffers();
  65381. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65382. // Draw order
  65383. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65384. pp.onAfterRenderObservable.notifyObservers(effect);
  65385. }
  65386. }
  65387. // Restore states
  65388. engine.setDepthBuffer(true);
  65389. engine.setDepthWrite(true);
  65390. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65391. };
  65392. /**
  65393. * Disposes of the post process manager.
  65394. */
  65395. PostProcessManager.prototype.dispose = function () {
  65396. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65397. if (buffer) {
  65398. buffer.dispose();
  65399. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65400. }
  65401. if (this._indexBuffer) {
  65402. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65403. this._indexBuffer = null;
  65404. }
  65405. };
  65406. return PostProcessManager;
  65407. }());
  65408. BABYLON.PostProcessManager = PostProcessManager;
  65409. })(BABYLON || (BABYLON = {}));
  65410. //# sourceMappingURL=babylon.postProcessManager.js.map
  65411. var BABYLON;
  65412. (function (BABYLON) {
  65413. /**
  65414. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65415. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65416. */
  65417. var PostProcess = /** @class */ (function () {
  65418. /**
  65419. * Creates a new instance PostProcess
  65420. * @param name The name of the PostProcess.
  65421. * @param fragmentUrl The url of the fragment shader to be used.
  65422. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65423. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65424. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65425. * @param camera The camera to apply the render pass to.
  65426. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65427. * @param engine The engine which the post process will be applied. (default: current engine)
  65428. * @param reusable If the post process can be reused on the same frame. (default: false)
  65429. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65430. * @param textureType Type of textures used when performing the post process. (default: 0)
  65431. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65432. * @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
  65433. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65434. */
  65435. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65436. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65437. if (defines === void 0) { defines = null; }
  65438. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65439. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65440. if (blockCompilation === void 0) { blockCompilation = false; }
  65441. this.name = name;
  65442. /**
  65443. * Width of the texture to apply the post process on
  65444. */
  65445. this.width = -1;
  65446. /**
  65447. * Height of the texture to apply the post process on
  65448. */
  65449. this.height = -1;
  65450. /**
  65451. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65452. */
  65453. this._outputTexture = null;
  65454. /**
  65455. * If the buffer needs to be cleared before applying the post process. (default: true)
  65456. * Should be set to false if shader will overwrite all previous pixels.
  65457. */
  65458. this.autoClear = true;
  65459. /**
  65460. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65461. */
  65462. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65463. /**
  65464. * Animations to be used for the post processing
  65465. */
  65466. this.animations = new Array();
  65467. /**
  65468. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65469. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65470. */
  65471. this.enablePixelPerfectMode = false;
  65472. /**
  65473. * Force the postprocess to be applied without taking in account viewport
  65474. */
  65475. this.forceFullscreenViewport = true;
  65476. /**
  65477. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65478. *
  65479. * | Value | Type | Description |
  65480. * | ----- | ----------------------------------- | ----------- |
  65481. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65482. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65483. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65484. *
  65485. */
  65486. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65487. /**
  65488. * Force textures to be a power of two (default: false)
  65489. */
  65490. this.alwaysForcePOT = false;
  65491. /**
  65492. * Number of sample textures (default: 1)
  65493. */
  65494. this.samples = 1;
  65495. /**
  65496. * Modify the scale of the post process to be the same as the viewport (default: false)
  65497. */
  65498. this.adaptScaleToCurrentViewport = false;
  65499. this._reusable = false;
  65500. /**
  65501. * Smart array of input and output textures for the post process.
  65502. */
  65503. this._textures = new BABYLON.SmartArray(2);
  65504. /**
  65505. * The index in _textures that corresponds to the output texture.
  65506. */
  65507. this._currentRenderTextureInd = 0;
  65508. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65509. this._texelSize = BABYLON.Vector2.Zero();
  65510. // Events
  65511. /**
  65512. * An event triggered when the postprocess is activated.
  65513. */
  65514. this.onActivateObservable = new BABYLON.Observable();
  65515. /**
  65516. * An event triggered when the postprocess changes its size.
  65517. */
  65518. this.onSizeChangedObservable = new BABYLON.Observable();
  65519. /**
  65520. * An event triggered when the postprocess applies its effect.
  65521. */
  65522. this.onApplyObservable = new BABYLON.Observable();
  65523. /**
  65524. * An event triggered before rendering the postprocess
  65525. */
  65526. this.onBeforeRenderObservable = new BABYLON.Observable();
  65527. /**
  65528. * An event triggered after rendering the postprocess
  65529. */
  65530. this.onAfterRenderObservable = new BABYLON.Observable();
  65531. if (camera != null) {
  65532. this._camera = camera;
  65533. this._scene = camera.getScene();
  65534. camera.attachPostProcess(this);
  65535. this._engine = this._scene.getEngine();
  65536. this._scene.postProcesses.push(this);
  65537. }
  65538. else if (engine) {
  65539. this._engine = engine;
  65540. this._engine.postProcesses.push(this);
  65541. }
  65542. this._options = options;
  65543. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65544. this._reusable = reusable || false;
  65545. this._textureType = textureType;
  65546. this._samplers = samplers || [];
  65547. this._samplers.push("textureSampler");
  65548. this._fragmentUrl = fragmentUrl;
  65549. this._vertexUrl = vertexUrl;
  65550. this._parameters = parameters || [];
  65551. this._parameters.push("scale");
  65552. this._indexParameters = indexParameters;
  65553. if (!blockCompilation) {
  65554. this.updateEffect(defines);
  65555. }
  65556. }
  65557. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65558. /**
  65559. * A function that is added to the onActivateObservable
  65560. */
  65561. set: function (callback) {
  65562. if (this._onActivateObserver) {
  65563. this.onActivateObservable.remove(this._onActivateObserver);
  65564. }
  65565. if (callback) {
  65566. this._onActivateObserver = this.onActivateObservable.add(callback);
  65567. }
  65568. },
  65569. enumerable: true,
  65570. configurable: true
  65571. });
  65572. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65573. /**
  65574. * A function that is added to the onSizeChangedObservable
  65575. */
  65576. set: function (callback) {
  65577. if (this._onSizeChangedObserver) {
  65578. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65579. }
  65580. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65581. },
  65582. enumerable: true,
  65583. configurable: true
  65584. });
  65585. Object.defineProperty(PostProcess.prototype, "onApply", {
  65586. /**
  65587. * A function that is added to the onApplyObservable
  65588. */
  65589. set: function (callback) {
  65590. if (this._onApplyObserver) {
  65591. this.onApplyObservable.remove(this._onApplyObserver);
  65592. }
  65593. this._onApplyObserver = this.onApplyObservable.add(callback);
  65594. },
  65595. enumerable: true,
  65596. configurable: true
  65597. });
  65598. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65599. /**
  65600. * A function that is added to the onBeforeRenderObservable
  65601. */
  65602. set: function (callback) {
  65603. if (this._onBeforeRenderObserver) {
  65604. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65605. }
  65606. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65607. },
  65608. enumerable: true,
  65609. configurable: true
  65610. });
  65611. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65612. /**
  65613. * A function that is added to the onAfterRenderObservable
  65614. */
  65615. set: function (callback) {
  65616. if (this._onAfterRenderObserver) {
  65617. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65618. }
  65619. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65620. },
  65621. enumerable: true,
  65622. configurable: true
  65623. });
  65624. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65625. /**
  65626. * 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
  65627. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65628. */
  65629. get: function () {
  65630. return this._textures.data[this._currentRenderTextureInd];
  65631. },
  65632. set: function (value) {
  65633. this._forcedOutputTexture = value;
  65634. },
  65635. enumerable: true,
  65636. configurable: true
  65637. });
  65638. /**
  65639. * Gets the camera which post process is applied to.
  65640. * @returns The camera the post process is applied to.
  65641. */
  65642. PostProcess.prototype.getCamera = function () {
  65643. return this._camera;
  65644. };
  65645. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65646. /**
  65647. * Gets the texel size of the postprocess.
  65648. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65649. */
  65650. get: function () {
  65651. if (this._shareOutputWithPostProcess) {
  65652. return this._shareOutputWithPostProcess.texelSize;
  65653. }
  65654. if (this._forcedOutputTexture) {
  65655. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65656. }
  65657. return this._texelSize;
  65658. },
  65659. enumerable: true,
  65660. configurable: true
  65661. });
  65662. /**
  65663. * Gets the engine which this post process belongs to.
  65664. * @returns The engine the post process was enabled with.
  65665. */
  65666. PostProcess.prototype.getEngine = function () {
  65667. return this._engine;
  65668. };
  65669. /**
  65670. * The effect that is created when initializing the post process.
  65671. * @returns The created effect corrisponding the the postprocess.
  65672. */
  65673. PostProcess.prototype.getEffect = function () {
  65674. return this._effect;
  65675. };
  65676. /**
  65677. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65678. * @param postProcess The post process to share the output with.
  65679. * @returns This post process.
  65680. */
  65681. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65682. this._disposeTextures();
  65683. this._shareOutputWithPostProcess = postProcess;
  65684. return this;
  65685. };
  65686. /**
  65687. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65688. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65689. */
  65690. PostProcess.prototype.useOwnOutput = function () {
  65691. if (this._textures.length == 0) {
  65692. this._textures = new BABYLON.SmartArray(2);
  65693. }
  65694. this._shareOutputWithPostProcess = null;
  65695. };
  65696. /**
  65697. * Updates the effect with the current post process compile time values and recompiles the shader.
  65698. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65699. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65700. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65701. * @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
  65702. * @param onCompiled Called when the shader has been compiled.
  65703. * @param onError Called if there is an error when compiling a shader.
  65704. */
  65705. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65706. if (defines === void 0) { defines = null; }
  65707. if (uniforms === void 0) { uniforms = null; }
  65708. if (samplers === void 0) { samplers = null; }
  65709. 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);
  65710. };
  65711. /**
  65712. * The post process is reusable if it can be used multiple times within one frame.
  65713. * @returns If the post process is reusable
  65714. */
  65715. PostProcess.prototype.isReusable = function () {
  65716. return this._reusable;
  65717. };
  65718. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65719. PostProcess.prototype.markTextureDirty = function () {
  65720. this.width = -1;
  65721. };
  65722. /**
  65723. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65724. * 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.
  65725. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65726. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65727. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65728. * @returns The target texture that was bound to be written to.
  65729. */
  65730. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65731. var _this = this;
  65732. if (sourceTexture === void 0) { sourceTexture = null; }
  65733. camera = camera || this._camera;
  65734. var scene = camera.getScene();
  65735. var engine = scene.getEngine();
  65736. var maxSize = engine.getCaps().maxTextureSize;
  65737. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65738. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65739. // 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
  65740. var webVRCamera = camera.parent;
  65741. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65742. requiredWidth /= 2;
  65743. }
  65744. var desiredWidth = (this._options.width || requiredWidth);
  65745. var desiredHeight = this._options.height || requiredHeight;
  65746. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65747. if (this.adaptScaleToCurrentViewport) {
  65748. var currentViewport = engine.currentViewport;
  65749. if (currentViewport) {
  65750. desiredWidth *= currentViewport.width;
  65751. desiredHeight *= currentViewport.height;
  65752. }
  65753. }
  65754. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65755. if (!this._options.width) {
  65756. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65757. }
  65758. if (!this._options.height) {
  65759. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65760. }
  65761. }
  65762. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65763. if (this._textures.length > 0) {
  65764. for (var i = 0; i < this._textures.length; i++) {
  65765. this._engine._releaseTexture(this._textures.data[i]);
  65766. }
  65767. this._textures.reset();
  65768. }
  65769. this.width = desiredWidth;
  65770. this.height = desiredHeight;
  65771. var textureSize = { width: this.width, height: this.height };
  65772. var textureOptions = {
  65773. generateMipMaps: false,
  65774. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65775. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65776. samplingMode: this.renderTargetSamplingMode,
  65777. type: this._textureType
  65778. };
  65779. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65780. if (this._reusable) {
  65781. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65782. }
  65783. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65784. this.onSizeChangedObservable.notifyObservers(this);
  65785. }
  65786. this._textures.forEach(function (texture) {
  65787. if (texture.samples !== _this.samples) {
  65788. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65789. }
  65790. });
  65791. }
  65792. var target;
  65793. if (this._shareOutputWithPostProcess) {
  65794. target = this._shareOutputWithPostProcess.inputTexture;
  65795. }
  65796. else if (this._forcedOutputTexture) {
  65797. target = this._forcedOutputTexture;
  65798. this.width = this._forcedOutputTexture.width;
  65799. this.height = this._forcedOutputTexture.height;
  65800. }
  65801. else {
  65802. target = this.inputTexture;
  65803. }
  65804. // Bind the input of this post process to be used as the output of the previous post process.
  65805. if (this.enablePixelPerfectMode) {
  65806. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65807. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65808. }
  65809. else {
  65810. this._scaleRatio.copyFromFloats(1, 1);
  65811. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65812. }
  65813. this.onActivateObservable.notifyObservers(camera);
  65814. // Clear
  65815. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65816. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65817. }
  65818. if (this._reusable) {
  65819. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65820. }
  65821. return target;
  65822. };
  65823. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65824. /**
  65825. * If the post process is supported.
  65826. */
  65827. get: function () {
  65828. return this._effect.isSupported;
  65829. },
  65830. enumerable: true,
  65831. configurable: true
  65832. });
  65833. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65834. /**
  65835. * The aspect ratio of the output texture.
  65836. */
  65837. get: function () {
  65838. if (this._shareOutputWithPostProcess) {
  65839. return this._shareOutputWithPostProcess.aspectRatio;
  65840. }
  65841. if (this._forcedOutputTexture) {
  65842. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65843. }
  65844. return this.width / this.height;
  65845. },
  65846. enumerable: true,
  65847. configurable: true
  65848. });
  65849. /**
  65850. * Get a value indicating if the post-process is ready to be used
  65851. * @returns true if the post-process is ready (shader is compiled)
  65852. */
  65853. PostProcess.prototype.isReady = function () {
  65854. return this._effect && this._effect.isReady();
  65855. };
  65856. /**
  65857. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65858. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65859. */
  65860. PostProcess.prototype.apply = function () {
  65861. // Check
  65862. if (!this._effect || !this._effect.isReady())
  65863. return null;
  65864. // States
  65865. this._engine.enableEffect(this._effect);
  65866. this._engine.setState(false);
  65867. this._engine.setDepthBuffer(false);
  65868. this._engine.setDepthWrite(false);
  65869. // Alpha
  65870. this._engine.setAlphaMode(this.alphaMode);
  65871. if (this.alphaConstants) {
  65872. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65873. }
  65874. // Bind the output texture of the preivous post process as the input to this post process.
  65875. var source;
  65876. if (this._shareOutputWithPostProcess) {
  65877. source = this._shareOutputWithPostProcess.inputTexture;
  65878. }
  65879. else if (this._forcedOutputTexture) {
  65880. source = this._forcedOutputTexture;
  65881. }
  65882. else {
  65883. source = this.inputTexture;
  65884. }
  65885. this._effect._bindTexture("textureSampler", source);
  65886. // Parameters
  65887. this._effect.setVector2("scale", this._scaleRatio);
  65888. this.onApplyObservable.notifyObservers(this._effect);
  65889. return this._effect;
  65890. };
  65891. PostProcess.prototype._disposeTextures = function () {
  65892. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65893. return;
  65894. }
  65895. if (this._textures.length > 0) {
  65896. for (var i = 0; i < this._textures.length; i++) {
  65897. this._engine._releaseTexture(this._textures.data[i]);
  65898. }
  65899. }
  65900. this._textures.dispose();
  65901. };
  65902. /**
  65903. * Disposes the post process.
  65904. * @param camera The camera to dispose the post process on.
  65905. */
  65906. PostProcess.prototype.dispose = function (camera) {
  65907. camera = camera || this._camera;
  65908. this._disposeTextures();
  65909. if (this._scene) {
  65910. var index_1 = this._scene.postProcesses.indexOf(this);
  65911. if (index_1 !== -1) {
  65912. this._scene.postProcesses.splice(index_1, 1);
  65913. }
  65914. }
  65915. else {
  65916. var index_2 = this._engine.postProcesses.indexOf(this);
  65917. if (index_2 !== -1) {
  65918. this._engine.postProcesses.splice(index_2, 1);
  65919. }
  65920. }
  65921. if (!camera) {
  65922. return;
  65923. }
  65924. camera.detachPostProcess(this);
  65925. var index = camera._postProcesses.indexOf(this);
  65926. if (index === 0 && camera._postProcesses.length > 0) {
  65927. var firstPostProcess = this._camera._getFirstPostProcess();
  65928. if (firstPostProcess) {
  65929. firstPostProcess.markTextureDirty();
  65930. }
  65931. }
  65932. this.onActivateObservable.clear();
  65933. this.onAfterRenderObservable.clear();
  65934. this.onApplyObservable.clear();
  65935. this.onBeforeRenderObservable.clear();
  65936. this.onSizeChangedObservable.clear();
  65937. };
  65938. return PostProcess;
  65939. }());
  65940. BABYLON.PostProcess = PostProcess;
  65941. })(BABYLON || (BABYLON = {}));
  65942. //# sourceMappingURL=babylon.postProcess.js.map
  65943. var BABYLON;
  65944. (function (BABYLON) {
  65945. var PassPostProcess = /** @class */ (function (_super) {
  65946. __extends(PassPostProcess, _super);
  65947. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65948. if (camera === void 0) { camera = null; }
  65949. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65950. if (blockCompilation === void 0) { blockCompilation = false; }
  65951. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65952. }
  65953. return PassPostProcess;
  65954. }(BABYLON.PostProcess));
  65955. BABYLON.PassPostProcess = PassPostProcess;
  65956. })(BABYLON || (BABYLON = {}));
  65957. //# sourceMappingURL=babylon.passPostProcess.js.map
  65958. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65959. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65960. s = arguments[i];
  65961. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65962. t[p] = s[p];
  65963. }
  65964. return t;
  65965. };
  65966. var BABYLON;
  65967. (function (BABYLON) {
  65968. /**
  65969. * Default implementation IShadowGenerator.
  65970. * This is the main object responsible of generating shadows in the framework.
  65971. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65972. */
  65973. var ShadowGenerator = /** @class */ (function () {
  65974. /**
  65975. * Creates a ShadowGenerator object.
  65976. * A ShadowGenerator is the required tool to use the shadows.
  65977. * Each light casting shadows needs to use its own ShadowGenerator.
  65978. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65979. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65980. * @param light The light object generating the shadows.
  65981. * @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.
  65982. */
  65983. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65984. this._bias = 0.00005;
  65985. this._normalBias = 0;
  65986. this._blurBoxOffset = 1;
  65987. this._blurScale = 2;
  65988. this._blurKernel = 1;
  65989. this._useKernelBlur = false;
  65990. this._filter = ShadowGenerator.FILTER_NONE;
  65991. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65992. this._contactHardeningLightSizeUVRatio = 0.1;
  65993. this._darkness = 0;
  65994. this._transparencyShadow = false;
  65995. /**
  65996. * Controls the extent to which the shadows fade out at the edge of the frustum
  65997. * Used only by directionals and spots
  65998. */
  65999. this.frustumEdgeFalloff = 0;
  66000. /**
  66001. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66002. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66003. * It might on the other hand introduce peter panning.
  66004. */
  66005. this.forceBackFacesOnly = false;
  66006. this._lightDirection = BABYLON.Vector3.Zero();
  66007. this._viewMatrix = BABYLON.Matrix.Zero();
  66008. this._projectionMatrix = BABYLON.Matrix.Zero();
  66009. this._transformMatrix = BABYLON.Matrix.Zero();
  66010. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66011. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66012. this._currentFaceIndex = 0;
  66013. this._currentFaceIndexCache = 0;
  66014. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66015. this._mapSize = mapSize;
  66016. this._light = light;
  66017. this._scene = light.getScene();
  66018. light._shadowGenerator = this;
  66019. // Texture type fallback from float to int if not supported.
  66020. var caps = this._scene.getEngine().getCaps();
  66021. if (!useFullFloatFirst) {
  66022. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66023. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66024. }
  66025. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66026. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66027. }
  66028. else {
  66029. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66030. }
  66031. }
  66032. else {
  66033. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66034. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66035. }
  66036. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66037. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66038. }
  66039. else {
  66040. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66041. }
  66042. }
  66043. this._initializeGenerator();
  66044. this._applyFilterValues();
  66045. }
  66046. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66047. /**
  66048. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66049. */
  66050. get: function () {
  66051. return this._bias;
  66052. },
  66053. /**
  66054. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66055. */
  66056. set: function (bias) {
  66057. this._bias = bias;
  66058. },
  66059. enumerable: true,
  66060. configurable: true
  66061. });
  66062. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66063. /**
  66064. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66065. */
  66066. get: function () {
  66067. return this._normalBias;
  66068. },
  66069. /**
  66070. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66071. */
  66072. set: function (normalBias) {
  66073. this._normalBias = normalBias;
  66074. },
  66075. enumerable: true,
  66076. configurable: true
  66077. });
  66078. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66079. /**
  66080. * Gets the blur box offset: offset applied during the blur pass.
  66081. * Only usefull if useKernelBlur = false
  66082. */
  66083. get: function () {
  66084. return this._blurBoxOffset;
  66085. },
  66086. /**
  66087. * Sets the blur box offset: offset applied during the blur pass.
  66088. * Only usefull if useKernelBlur = false
  66089. */
  66090. set: function (value) {
  66091. if (this._blurBoxOffset === value) {
  66092. return;
  66093. }
  66094. this._blurBoxOffset = value;
  66095. this._disposeBlurPostProcesses();
  66096. },
  66097. enumerable: true,
  66098. configurable: true
  66099. });
  66100. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66101. /**
  66102. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66103. * 2 means half of the size.
  66104. */
  66105. get: function () {
  66106. return this._blurScale;
  66107. },
  66108. /**
  66109. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66110. * 2 means half of the size.
  66111. */
  66112. set: function (value) {
  66113. if (this._blurScale === value) {
  66114. return;
  66115. }
  66116. this._blurScale = value;
  66117. this._disposeBlurPostProcesses();
  66118. },
  66119. enumerable: true,
  66120. configurable: true
  66121. });
  66122. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66123. /**
  66124. * Gets the blur kernel: kernel size of the blur pass.
  66125. * Only usefull if useKernelBlur = true
  66126. */
  66127. get: function () {
  66128. return this._blurKernel;
  66129. },
  66130. /**
  66131. * Sets the blur kernel: kernel size of the blur pass.
  66132. * Only usefull if useKernelBlur = true
  66133. */
  66134. set: function (value) {
  66135. if (this._blurKernel === value) {
  66136. return;
  66137. }
  66138. this._blurKernel = value;
  66139. this._disposeBlurPostProcesses();
  66140. },
  66141. enumerable: true,
  66142. configurable: true
  66143. });
  66144. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66145. /**
  66146. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66147. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66148. */
  66149. get: function () {
  66150. return this._useKernelBlur;
  66151. },
  66152. /**
  66153. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66154. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66155. */
  66156. set: function (value) {
  66157. if (this._useKernelBlur === value) {
  66158. return;
  66159. }
  66160. this._useKernelBlur = value;
  66161. this._disposeBlurPostProcesses();
  66162. },
  66163. enumerable: true,
  66164. configurable: true
  66165. });
  66166. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66167. /**
  66168. * Gets the depth scale used in ESM mode.
  66169. */
  66170. get: function () {
  66171. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66172. },
  66173. /**
  66174. * Sets the depth scale used in ESM mode.
  66175. * This can override the scale stored on the light.
  66176. */
  66177. set: function (value) {
  66178. this._depthScale = value;
  66179. },
  66180. enumerable: true,
  66181. configurable: true
  66182. });
  66183. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66184. /**
  66185. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66186. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66187. */
  66188. get: function () {
  66189. return this._filter;
  66190. },
  66191. /**
  66192. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66193. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66194. */
  66195. set: function (value) {
  66196. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66197. if (this._light.needCube()) {
  66198. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66199. this.useExponentialShadowMap = true;
  66200. return;
  66201. }
  66202. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66203. this.useCloseExponentialShadowMap = true;
  66204. return;
  66205. }
  66206. // PCF on cubemap would also be expensive
  66207. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66208. this.usePoissonSampling = true;
  66209. return;
  66210. }
  66211. }
  66212. // Weblg1 fallback for PCF.
  66213. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66214. if (this._scene.getEngine().webGLVersion === 1) {
  66215. this.usePoissonSampling = true;
  66216. return;
  66217. }
  66218. }
  66219. if (this._filter === value) {
  66220. return;
  66221. }
  66222. this._filter = value;
  66223. this._disposeBlurPostProcesses();
  66224. this._applyFilterValues();
  66225. this._light._markMeshesAsLightDirty();
  66226. },
  66227. enumerable: true,
  66228. configurable: true
  66229. });
  66230. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66231. /**
  66232. * Gets if the current filter is set to Poisson Sampling.
  66233. */
  66234. get: function () {
  66235. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66236. },
  66237. /**
  66238. * Sets the current filter to Poisson Sampling.
  66239. */
  66240. set: function (value) {
  66241. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66242. return;
  66243. }
  66244. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66245. },
  66246. enumerable: true,
  66247. configurable: true
  66248. });
  66249. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66250. /**
  66251. * Gets if the current filter is set to VSM.
  66252. * DEPRECATED. Should use useExponentialShadowMap instead.
  66253. */
  66254. get: function () {
  66255. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66256. return this.useExponentialShadowMap;
  66257. },
  66258. /**
  66259. * Sets the current filter is to VSM.
  66260. * DEPRECATED. Should use useExponentialShadowMap instead.
  66261. */
  66262. set: function (value) {
  66263. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66264. this.useExponentialShadowMap = value;
  66265. },
  66266. enumerable: true,
  66267. configurable: true
  66268. });
  66269. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66270. /**
  66271. * Gets if the current filter is set to blurred VSM.
  66272. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66273. */
  66274. get: function () {
  66275. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66276. return this.useBlurExponentialShadowMap;
  66277. },
  66278. /**
  66279. * Sets the current filter is to blurred VSM.
  66280. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66281. */
  66282. set: function (value) {
  66283. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66284. this.useBlurExponentialShadowMap = value;
  66285. },
  66286. enumerable: true,
  66287. configurable: true
  66288. });
  66289. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66290. /**
  66291. * Gets if the current filter is set to ESM.
  66292. */
  66293. get: function () {
  66294. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66295. },
  66296. /**
  66297. * Sets the current filter is to ESM.
  66298. */
  66299. set: function (value) {
  66300. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66301. return;
  66302. }
  66303. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66304. },
  66305. enumerable: true,
  66306. configurable: true
  66307. });
  66308. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66309. /**
  66310. * Gets if the current filter is set to filtered ESM.
  66311. */
  66312. get: function () {
  66313. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66314. },
  66315. /**
  66316. * Gets if the current filter is set to filtered ESM.
  66317. */
  66318. set: function (value) {
  66319. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66320. return;
  66321. }
  66322. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66323. },
  66324. enumerable: true,
  66325. configurable: true
  66326. });
  66327. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66328. /**
  66329. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66330. * exponential to prevent steep falloff artifacts).
  66331. */
  66332. get: function () {
  66333. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66334. },
  66335. /**
  66336. * Sets the current filter to "close ESM" (using the inverse of the
  66337. * exponential to prevent steep falloff artifacts).
  66338. */
  66339. set: function (value) {
  66340. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66341. return;
  66342. }
  66343. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66344. },
  66345. enumerable: true,
  66346. configurable: true
  66347. });
  66348. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66349. /**
  66350. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66351. * exponential to prevent steep falloff artifacts).
  66352. */
  66353. get: function () {
  66354. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66355. },
  66356. /**
  66357. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66358. * exponential to prevent steep falloff artifacts).
  66359. */
  66360. set: function (value) {
  66361. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66362. return;
  66363. }
  66364. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66365. },
  66366. enumerable: true,
  66367. configurable: true
  66368. });
  66369. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66370. /**
  66371. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66372. */
  66373. get: function () {
  66374. return this.filter === ShadowGenerator.FILTER_PCF;
  66375. },
  66376. /**
  66377. * Sets the current filter to "PCF" (percentage closer filtering).
  66378. */
  66379. set: function (value) {
  66380. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66381. return;
  66382. }
  66383. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66384. },
  66385. enumerable: true,
  66386. configurable: true
  66387. });
  66388. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66389. /**
  66390. * Gets the PCF or PCSS Quality.
  66391. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66392. */
  66393. get: function () {
  66394. return this._filteringQuality;
  66395. },
  66396. /**
  66397. * Sets the PCF or PCSS Quality.
  66398. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66399. */
  66400. set: function (filteringQuality) {
  66401. this._filteringQuality = filteringQuality;
  66402. },
  66403. enumerable: true,
  66404. configurable: true
  66405. });
  66406. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66407. /**
  66408. * Gets if the current filter is set to "PCSS" (contact hardening).
  66409. */
  66410. get: function () {
  66411. return this.filter === ShadowGenerator.FILTER_PCSS;
  66412. },
  66413. /**
  66414. * Sets the current filter to "PCSS" (contact hardening).
  66415. */
  66416. set: function (value) {
  66417. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66418. return;
  66419. }
  66420. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66421. },
  66422. enumerable: true,
  66423. configurable: true
  66424. });
  66425. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66426. /**
  66427. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66428. * Using a ratio helps keeping shape stability independently of the map size.
  66429. *
  66430. * It does not account for the light projection as it was having too much
  66431. * instability during the light setup or during light position changes.
  66432. *
  66433. * Only valid if useContactHardeningShadow is true.
  66434. */
  66435. get: function () {
  66436. return this._contactHardeningLightSizeUVRatio;
  66437. },
  66438. /**
  66439. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66440. * Using a ratio helps keeping shape stability independently of the map size.
  66441. *
  66442. * It does not account for the light projection as it was having too much
  66443. * instability during the light setup or during light position changes.
  66444. *
  66445. * Only valid if useContactHardeningShadow is true.
  66446. */
  66447. set: function (contactHardeningLightSizeUVRatio) {
  66448. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66449. },
  66450. enumerable: true,
  66451. configurable: true
  66452. });
  66453. /**
  66454. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66455. * 0 means strongest and 1 would means no shadow.
  66456. * @returns the darkness.
  66457. */
  66458. ShadowGenerator.prototype.getDarkness = function () {
  66459. return this._darkness;
  66460. };
  66461. /**
  66462. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66463. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66464. * @returns the shadow generator allowing fluent coding.
  66465. */
  66466. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66467. if (darkness >= 1.0)
  66468. this._darkness = 1.0;
  66469. else if (darkness <= 0.0)
  66470. this._darkness = 0.0;
  66471. else
  66472. this._darkness = darkness;
  66473. return this;
  66474. };
  66475. /**
  66476. * Sets the ability to have transparent shadow (boolean).
  66477. * @param transparent True if transparent else False
  66478. * @returns the shadow generator allowing fluent coding
  66479. */
  66480. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66481. this._transparencyShadow = transparent;
  66482. return this;
  66483. };
  66484. /**
  66485. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66486. * @returns The render target texture if present otherwise, null
  66487. */
  66488. ShadowGenerator.prototype.getShadowMap = function () {
  66489. return this._shadowMap;
  66490. };
  66491. /**
  66492. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66493. * @returns The render target texture if the shadow map is present otherwise, null
  66494. */
  66495. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66496. if (this._shadowMap2) {
  66497. return this._shadowMap2;
  66498. }
  66499. return this._shadowMap;
  66500. };
  66501. /**
  66502. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66503. * @param mesh Mesh to add
  66504. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66505. * @returns the Shadow Generator itself
  66506. */
  66507. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66508. if (includeDescendants === void 0) { includeDescendants = true; }
  66509. if (!this._shadowMap) {
  66510. return this;
  66511. }
  66512. if (!this._shadowMap.renderList) {
  66513. this._shadowMap.renderList = [];
  66514. }
  66515. this._shadowMap.renderList.push(mesh);
  66516. if (includeDescendants) {
  66517. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66518. }
  66519. return this;
  66520. var _a;
  66521. };
  66522. /**
  66523. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66524. * @param mesh Mesh to remove
  66525. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66526. * @returns the Shadow Generator itself
  66527. */
  66528. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66529. if (includeDescendants === void 0) { includeDescendants = true; }
  66530. if (!this._shadowMap || !this._shadowMap.renderList) {
  66531. return this;
  66532. }
  66533. var index = this._shadowMap.renderList.indexOf(mesh);
  66534. if (index !== -1) {
  66535. this._shadowMap.renderList.splice(index, 1);
  66536. }
  66537. if (includeDescendants) {
  66538. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66539. var child = _a[_i];
  66540. this.removeShadowCaster(child);
  66541. }
  66542. }
  66543. return this;
  66544. };
  66545. /**
  66546. * Returns the associated light object.
  66547. * @returns the light generating the shadow
  66548. */
  66549. ShadowGenerator.prototype.getLight = function () {
  66550. return this._light;
  66551. };
  66552. ShadowGenerator.prototype._initializeGenerator = function () {
  66553. this._light._markMeshesAsLightDirty();
  66554. this._initializeShadowMap();
  66555. };
  66556. ShadowGenerator.prototype._initializeShadowMap = function () {
  66557. var _this = this;
  66558. // Render target
  66559. var engine = this._scene.getEngine();
  66560. if (engine.webGLVersion > 1) {
  66561. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66562. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66563. }
  66564. else {
  66565. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66566. }
  66567. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66568. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66569. this._shadowMap.anisotropicFilteringLevel = 1;
  66570. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66571. this._shadowMap.renderParticles = false;
  66572. this._shadowMap.ignoreCameraViewport = true;
  66573. // Record Face Index before render.
  66574. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66575. _this._currentFaceIndex = faceIndex;
  66576. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66577. engine.setColorWrite(false);
  66578. }
  66579. });
  66580. // Custom render function.
  66581. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66582. // Blur if required afer render.
  66583. this._shadowMap.onAfterUnbindObservable.add(function () {
  66584. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66585. engine.setColorWrite(true);
  66586. }
  66587. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66588. return;
  66589. }
  66590. var shadowMap = _this.getShadowMapForRendering();
  66591. if (shadowMap) {
  66592. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66593. }
  66594. });
  66595. // Clear according to the chosen filter.
  66596. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66597. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66598. this._shadowMap.onClearObservable.add(function (engine) {
  66599. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66600. engine.clear(clearOne, false, true, false);
  66601. }
  66602. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66603. engine.clear(clearZero, true, true, false);
  66604. }
  66605. else {
  66606. engine.clear(clearOne, true, true, false);
  66607. }
  66608. });
  66609. };
  66610. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66611. var _this = this;
  66612. var engine = this._scene.getEngine();
  66613. var targetSize = this._mapSize / this.blurScale;
  66614. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66615. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66616. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66617. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66618. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66619. }
  66620. if (this.useKernelBlur) {
  66621. 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);
  66622. this._kernelBlurXPostprocess.width = targetSize;
  66623. this._kernelBlurXPostprocess.height = targetSize;
  66624. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66625. effect.setTexture("textureSampler", _this._shadowMap);
  66626. });
  66627. 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);
  66628. this._kernelBlurXPostprocess.autoClear = false;
  66629. this._kernelBlurYPostprocess.autoClear = false;
  66630. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66631. this._kernelBlurXPostprocess.packedFloat = true;
  66632. this._kernelBlurYPostprocess.packedFloat = true;
  66633. }
  66634. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66635. }
  66636. else {
  66637. 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);
  66638. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66639. effect.setFloat2("screenSize", targetSize, targetSize);
  66640. effect.setTexture("textureSampler", _this._shadowMap);
  66641. });
  66642. this._boxBlurPostprocess.autoClear = false;
  66643. this._blurPostProcesses = [this._boxBlurPostprocess];
  66644. }
  66645. };
  66646. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66647. var index;
  66648. var engine = this._scene.getEngine();
  66649. if (depthOnlySubMeshes.length) {
  66650. engine.setColorWrite(false);
  66651. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66652. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66653. }
  66654. engine.setColorWrite(true);
  66655. }
  66656. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66657. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66658. }
  66659. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66660. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66661. }
  66662. if (this._transparencyShadow) {
  66663. for (index = 0; index < transparentSubMeshes.length; index++) {
  66664. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66665. }
  66666. }
  66667. };
  66668. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66669. var _this = this;
  66670. var mesh = subMesh.getRenderingMesh();
  66671. var scene = this._scene;
  66672. var engine = scene.getEngine();
  66673. var material = subMesh.getMaterial();
  66674. if (!material) {
  66675. return;
  66676. }
  66677. // Culling
  66678. engine.setState(material.backFaceCulling);
  66679. // Managing instances
  66680. var batch = mesh._getInstancesRenderList(subMesh._id);
  66681. if (batch.mustReturn) {
  66682. return;
  66683. }
  66684. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66685. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66686. engine.enableEffect(this._effect);
  66687. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66688. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66689. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66690. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66691. this._effect.setVector3("lightData", this._cachedDirection);
  66692. }
  66693. else {
  66694. this._effect.setVector3("lightData", this._cachedPosition);
  66695. }
  66696. if (scene.activeCamera) {
  66697. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66698. }
  66699. // Alpha test
  66700. if (material && material.needAlphaTesting()) {
  66701. var alphaTexture = material.getAlphaTestTexture();
  66702. if (alphaTexture) {
  66703. this._effect.setTexture("diffuseSampler", alphaTexture);
  66704. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66705. }
  66706. }
  66707. // Bones
  66708. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66709. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66710. }
  66711. // Morph targets
  66712. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66713. if (this.forceBackFacesOnly) {
  66714. engine.setState(true, 0, false, true);
  66715. }
  66716. // Draw
  66717. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66718. if (this.forceBackFacesOnly) {
  66719. engine.setState(true, 0, false, false);
  66720. }
  66721. }
  66722. else {
  66723. // Need to reset refresh rate of the shadowMap
  66724. if (this._shadowMap) {
  66725. this._shadowMap.resetRefreshCounter();
  66726. }
  66727. }
  66728. };
  66729. ShadowGenerator.prototype._applyFilterValues = function () {
  66730. if (!this._shadowMap) {
  66731. return;
  66732. }
  66733. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66734. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66735. }
  66736. else {
  66737. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66738. }
  66739. };
  66740. /**
  66741. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66742. * @param onCompiled Callback triggered at the and of the effects compilation
  66743. * @param options Sets of optional options forcing the compilation with different modes
  66744. */
  66745. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66746. var _this = this;
  66747. var localOptions = __assign({ useInstances: false }, options);
  66748. var shadowMap = this.getShadowMap();
  66749. if (!shadowMap) {
  66750. if (onCompiled) {
  66751. onCompiled(this);
  66752. }
  66753. return;
  66754. }
  66755. var renderList = shadowMap.renderList;
  66756. if (!renderList) {
  66757. if (onCompiled) {
  66758. onCompiled(this);
  66759. }
  66760. return;
  66761. }
  66762. var subMeshes = new Array();
  66763. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66764. var mesh = renderList_1[_i];
  66765. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66766. }
  66767. if (subMeshes.length === 0) {
  66768. if (onCompiled) {
  66769. onCompiled(this);
  66770. }
  66771. return;
  66772. }
  66773. var currentIndex = 0;
  66774. var checkReady = function () {
  66775. if (!_this._scene || !_this._scene.getEngine()) {
  66776. return;
  66777. }
  66778. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66779. currentIndex++;
  66780. if (currentIndex >= subMeshes.length) {
  66781. if (onCompiled) {
  66782. onCompiled(_this);
  66783. }
  66784. return;
  66785. }
  66786. }
  66787. setTimeout(checkReady, 16);
  66788. };
  66789. checkReady();
  66790. };
  66791. /**
  66792. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66793. * @param options Sets of optional options forcing the compilation with different modes
  66794. * @returns A promise that resolves when the compilation completes
  66795. */
  66796. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66797. var _this = this;
  66798. return new Promise(function (resolve) {
  66799. _this.forceCompilation(function () {
  66800. resolve();
  66801. }, options);
  66802. });
  66803. };
  66804. /**
  66805. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66806. * @param subMesh The submesh we want to render in the shadow map
  66807. * @param useInstances Defines wether will draw in the map using instances
  66808. * @returns true if ready otherwise, false
  66809. */
  66810. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66811. var defines = [];
  66812. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66813. defines.push("#define FLOAT");
  66814. }
  66815. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66816. defines.push("#define ESM");
  66817. }
  66818. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66819. defines.push("#define DEPTHTEXTURE");
  66820. }
  66821. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66822. var mesh = subMesh.getMesh();
  66823. var material = subMesh.getMaterial();
  66824. // Normal bias.
  66825. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66826. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66827. defines.push("#define NORMAL");
  66828. if (mesh.nonUniformScaling) {
  66829. defines.push("#define NONUNIFORMSCALING");
  66830. }
  66831. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66832. defines.push("#define DIRECTIONINLIGHTDATA");
  66833. }
  66834. }
  66835. // Alpha test
  66836. if (material && material.needAlphaTesting()) {
  66837. var alphaTexture = material.getAlphaTestTexture();
  66838. if (alphaTexture) {
  66839. defines.push("#define ALPHATEST");
  66840. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66841. attribs.push(BABYLON.VertexBuffer.UVKind);
  66842. defines.push("#define UV1");
  66843. }
  66844. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66845. if (alphaTexture.coordinatesIndex === 1) {
  66846. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66847. defines.push("#define UV2");
  66848. }
  66849. }
  66850. }
  66851. }
  66852. // Bones
  66853. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66854. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66855. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66856. if (mesh.numBoneInfluencers > 4) {
  66857. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66858. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66859. }
  66860. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66861. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66862. }
  66863. else {
  66864. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66865. }
  66866. // Morph targets
  66867. var manager = mesh.morphTargetManager;
  66868. var morphInfluencers = 0;
  66869. if (manager) {
  66870. if (manager.numInfluencers > 0) {
  66871. defines.push("#define MORPHTARGETS");
  66872. morphInfluencers = manager.numInfluencers;
  66873. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66874. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66875. }
  66876. }
  66877. // Instances
  66878. if (useInstances) {
  66879. defines.push("#define INSTANCES");
  66880. attribs.push("world0");
  66881. attribs.push("world1");
  66882. attribs.push("world2");
  66883. attribs.push("world3");
  66884. }
  66885. // Get correct effect
  66886. var join = defines.join("\n");
  66887. if (this._cachedDefines !== join) {
  66888. this._cachedDefines = join;
  66889. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66890. }
  66891. if (!this._effect.isReady()) {
  66892. return false;
  66893. }
  66894. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66895. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66896. this._initializeBlurRTTAndPostProcesses();
  66897. }
  66898. }
  66899. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66900. return false;
  66901. }
  66902. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66903. return false;
  66904. }
  66905. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66906. return false;
  66907. }
  66908. return true;
  66909. };
  66910. /**
  66911. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66912. * @param defines Defines of the material we want to update
  66913. * @param lightIndex Index of the light in the enabled light list of the material
  66914. */
  66915. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66916. var scene = this._scene;
  66917. var light = this._light;
  66918. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66919. return;
  66920. }
  66921. defines["SHADOW" + lightIndex] = true;
  66922. if (this.useContactHardeningShadow) {
  66923. defines["SHADOWPCSS" + lightIndex] = true;
  66924. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66925. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66926. }
  66927. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66928. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66929. }
  66930. // else default to high.
  66931. }
  66932. if (this.usePercentageCloserFiltering) {
  66933. defines["SHADOWPCF" + lightIndex] = true;
  66934. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66935. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66936. }
  66937. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66938. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66939. }
  66940. // else default to high.
  66941. }
  66942. else if (this.usePoissonSampling) {
  66943. defines["SHADOWPOISSON" + lightIndex] = true;
  66944. }
  66945. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66946. defines["SHADOWESM" + lightIndex] = true;
  66947. }
  66948. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66949. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66950. }
  66951. if (light.needCube()) {
  66952. defines["SHADOWCUBE" + lightIndex] = true;
  66953. }
  66954. };
  66955. /**
  66956. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66957. * defined in the generator but impacting the effect).
  66958. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66959. * @param effect The effect we are binfing the information for
  66960. */
  66961. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66962. var light = this._light;
  66963. var scene = this._scene;
  66964. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66965. return;
  66966. }
  66967. var camera = scene.activeCamera;
  66968. if (!camera) {
  66969. return;
  66970. }
  66971. var shadowMap = this.getShadowMap();
  66972. if (!shadowMap) {
  66973. return;
  66974. }
  66975. if (!light.needCube()) {
  66976. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66977. }
  66978. // Only PCF uses depth stencil texture.
  66979. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66980. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66981. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66982. }
  66983. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66984. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66985. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66986. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66987. }
  66988. else {
  66989. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66990. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66991. }
  66992. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66993. };
  66994. /**
  66995. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66996. * (eq to shadow prjection matrix * light transform matrix)
  66997. * @returns The transform matrix used to create the shadow map
  66998. */
  66999. ShadowGenerator.prototype.getTransformMatrix = function () {
  67000. var scene = this._scene;
  67001. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67002. return this._transformMatrix;
  67003. }
  67004. this._currentRenderID = scene.getRenderId();
  67005. this._currentFaceIndexCache = this._currentFaceIndex;
  67006. var lightPosition = this._light.position;
  67007. if (this._light.computeTransformedInformation()) {
  67008. lightPosition = this._light.transformedPosition;
  67009. }
  67010. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67011. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67012. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67013. }
  67014. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67015. this._cachedPosition.copyFrom(lightPosition);
  67016. this._cachedDirection.copyFrom(this._lightDirection);
  67017. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67018. var shadowMap = this.getShadowMap();
  67019. if (shadowMap) {
  67020. var renderList = shadowMap.renderList;
  67021. if (renderList) {
  67022. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67023. }
  67024. }
  67025. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67026. }
  67027. return this._transformMatrix;
  67028. };
  67029. /**
  67030. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67031. * Cube and 2D textures for instance.
  67032. */
  67033. ShadowGenerator.prototype.recreateShadowMap = function () {
  67034. var shadowMap = this._shadowMap;
  67035. if (!shadowMap) {
  67036. return;
  67037. }
  67038. // Track render list.
  67039. var renderList = shadowMap.renderList;
  67040. // Clean up existing data.
  67041. this._disposeRTTandPostProcesses();
  67042. // Reinitializes.
  67043. this._initializeGenerator();
  67044. // Reaffect the filter to ensure a correct fallback if necessary.
  67045. this.filter = this.filter;
  67046. // Reaffect the filter.
  67047. this._applyFilterValues();
  67048. // Reaffect Render List.
  67049. this._shadowMap.renderList = renderList;
  67050. };
  67051. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67052. if (this._shadowMap2) {
  67053. this._shadowMap2.dispose();
  67054. this._shadowMap2 = null;
  67055. }
  67056. if (this._boxBlurPostprocess) {
  67057. this._boxBlurPostprocess.dispose();
  67058. this._boxBlurPostprocess = null;
  67059. }
  67060. if (this._kernelBlurXPostprocess) {
  67061. this._kernelBlurXPostprocess.dispose();
  67062. this._kernelBlurXPostprocess = null;
  67063. }
  67064. if (this._kernelBlurYPostprocess) {
  67065. this._kernelBlurYPostprocess.dispose();
  67066. this._kernelBlurYPostprocess = null;
  67067. }
  67068. this._blurPostProcesses = [];
  67069. };
  67070. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67071. if (this._shadowMap) {
  67072. this._shadowMap.dispose();
  67073. this._shadowMap = null;
  67074. }
  67075. this._disposeBlurPostProcesses();
  67076. };
  67077. /**
  67078. * Disposes the ShadowGenerator.
  67079. * Returns nothing.
  67080. */
  67081. ShadowGenerator.prototype.dispose = function () {
  67082. this._disposeRTTandPostProcesses();
  67083. if (this._light) {
  67084. this._light._shadowGenerator = null;
  67085. this._light._markMeshesAsLightDirty();
  67086. }
  67087. };
  67088. /**
  67089. * Serializes the shadow generator setup to a json object.
  67090. * @returns The serialized JSON object
  67091. */
  67092. ShadowGenerator.prototype.serialize = function () {
  67093. var serializationObject = {};
  67094. var shadowMap = this.getShadowMap();
  67095. if (!shadowMap) {
  67096. return serializationObject;
  67097. }
  67098. serializationObject.lightId = this._light.id;
  67099. serializationObject.mapSize = shadowMap.getRenderSize();
  67100. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67101. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67102. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67103. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67104. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67105. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67106. serializationObject.depthScale = this.depthScale;
  67107. serializationObject.darkness = this.getDarkness();
  67108. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67109. serializationObject.blurKernel = this.blurKernel;
  67110. serializationObject.blurScale = this.blurScale;
  67111. serializationObject.useKernelBlur = this.useKernelBlur;
  67112. serializationObject.transparencyShadow = this._transparencyShadow;
  67113. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67114. serializationObject.bias = this.bias;
  67115. serializationObject.normalBias = this.normalBias;
  67116. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67117. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67118. serializationObject.filteringQuality = this.filteringQuality;
  67119. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67120. serializationObject.renderList = [];
  67121. if (shadowMap.renderList) {
  67122. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67123. var mesh = shadowMap.renderList[meshIndex];
  67124. serializationObject.renderList.push(mesh.id);
  67125. }
  67126. }
  67127. return serializationObject;
  67128. };
  67129. /**
  67130. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67131. * @param parsedShadowGenerator The JSON object to parse
  67132. * @param scene The scene to create the shadow map for
  67133. * @returns The parsed shadow generator
  67134. */
  67135. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67136. //casting to point light, as light is missing the position attr and typescript complains.
  67137. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67138. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67139. var shadowMap = shadowGenerator.getShadowMap();
  67140. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67141. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67142. meshes.forEach(function (mesh) {
  67143. if (!shadowMap) {
  67144. return;
  67145. }
  67146. if (!shadowMap.renderList) {
  67147. shadowMap.renderList = [];
  67148. }
  67149. shadowMap.renderList.push(mesh);
  67150. });
  67151. }
  67152. if (parsedShadowGenerator.usePoissonSampling) {
  67153. shadowGenerator.usePoissonSampling = true;
  67154. }
  67155. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67156. shadowGenerator.useExponentialShadowMap = true;
  67157. }
  67158. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67159. shadowGenerator.useBlurExponentialShadowMap = true;
  67160. }
  67161. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67162. shadowGenerator.useCloseExponentialShadowMap = true;
  67163. }
  67164. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67165. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67166. }
  67167. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67168. shadowGenerator.usePercentageCloserFiltering = true;
  67169. }
  67170. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67171. shadowGenerator.useContactHardeningShadow = true;
  67172. }
  67173. if (parsedShadowGenerator.filteringQuality) {
  67174. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67175. }
  67176. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67177. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67178. }
  67179. // Backward compat
  67180. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67181. shadowGenerator.useExponentialShadowMap = true;
  67182. }
  67183. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67184. shadowGenerator.useBlurExponentialShadowMap = true;
  67185. }
  67186. if (parsedShadowGenerator.depthScale) {
  67187. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67188. }
  67189. if (parsedShadowGenerator.blurScale) {
  67190. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67191. }
  67192. if (parsedShadowGenerator.blurBoxOffset) {
  67193. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67194. }
  67195. if (parsedShadowGenerator.useKernelBlur) {
  67196. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67197. }
  67198. if (parsedShadowGenerator.blurKernel) {
  67199. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67200. }
  67201. if (parsedShadowGenerator.bias !== undefined) {
  67202. shadowGenerator.bias = parsedShadowGenerator.bias;
  67203. }
  67204. if (parsedShadowGenerator.normalBias !== undefined) {
  67205. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67206. }
  67207. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67208. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67209. }
  67210. if (parsedShadowGenerator.darkness) {
  67211. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67212. }
  67213. if (parsedShadowGenerator.transparencyShadow) {
  67214. shadowGenerator.setTransparencyShadow(true);
  67215. }
  67216. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67217. return shadowGenerator;
  67218. };
  67219. /**
  67220. * Shadow generator mode None: no filtering applied.
  67221. */
  67222. ShadowGenerator.FILTER_NONE = 0;
  67223. /**
  67224. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67225. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67226. */
  67227. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67228. /**
  67229. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67230. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67231. */
  67232. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67233. /**
  67234. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67235. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67236. */
  67237. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67238. /**
  67239. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67240. * edge artifacts on steep falloff.
  67241. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67242. */
  67243. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67244. /**
  67245. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67246. * edge artifacts on steep falloff.
  67247. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67248. */
  67249. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67250. /**
  67251. * Shadow generator mode PCF: Percentage Closer Filtering
  67252. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67253. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67254. */
  67255. ShadowGenerator.FILTER_PCF = 6;
  67256. /**
  67257. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67258. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67259. * Contact Hardening
  67260. */
  67261. ShadowGenerator.FILTER_PCSS = 7;
  67262. /**
  67263. * Reserved for PCF and PCSS
  67264. * Highest Quality.
  67265. *
  67266. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67267. *
  67268. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67269. */
  67270. ShadowGenerator.QUALITY_HIGH = 0;
  67271. /**
  67272. * Reserved for PCF and PCSS
  67273. * Good tradeoff for quality/perf cross devices
  67274. *
  67275. * Execute PCF on a 3*3 kernel.
  67276. *
  67277. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67278. */
  67279. ShadowGenerator.QUALITY_MEDIUM = 1;
  67280. /**
  67281. * Reserved for PCF and PCSS
  67282. * The lowest quality but the fastest.
  67283. *
  67284. * Execute PCF on a 1*1 kernel.
  67285. *
  67286. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67287. */
  67288. ShadowGenerator.QUALITY_LOW = 2;
  67289. return ShadowGenerator;
  67290. }());
  67291. BABYLON.ShadowGenerator = ShadowGenerator;
  67292. })(BABYLON || (BABYLON = {}));
  67293. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67294. var BABYLON;
  67295. (function (BABYLON) {
  67296. var DefaultLoadingScreen = /** @class */ (function () {
  67297. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67298. if (_loadingText === void 0) { _loadingText = ""; }
  67299. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67300. var _this = this;
  67301. this._renderingCanvas = _renderingCanvas;
  67302. this._loadingText = _loadingText;
  67303. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67304. // Resize
  67305. this._resizeLoadingUI = function () {
  67306. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67307. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67308. if (!_this._loadingDiv) {
  67309. return;
  67310. }
  67311. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67312. _this._loadingDiv.style.left = canvasRect.left + "px";
  67313. _this._loadingDiv.style.top = canvasRect.top + "px";
  67314. _this._loadingDiv.style.width = canvasRect.width + "px";
  67315. _this._loadingDiv.style.height = canvasRect.height + "px";
  67316. };
  67317. }
  67318. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67319. if (this._loadingDiv) {
  67320. // Do not add a loading screen if there is already one
  67321. return;
  67322. }
  67323. this._loadingDiv = document.createElement("div");
  67324. this._loadingDiv.id = "babylonjsLoadingDiv";
  67325. this._loadingDiv.style.opacity = "0";
  67326. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67327. this._loadingDiv.style.pointerEvents = "none";
  67328. // Loading text
  67329. this._loadingTextDiv = document.createElement("div");
  67330. this._loadingTextDiv.style.position = "absolute";
  67331. this._loadingTextDiv.style.left = "0";
  67332. this._loadingTextDiv.style.top = "50%";
  67333. this._loadingTextDiv.style.marginTop = "80px";
  67334. this._loadingTextDiv.style.width = "100%";
  67335. this._loadingTextDiv.style.height = "20px";
  67336. this._loadingTextDiv.style.fontFamily = "Arial";
  67337. this._loadingTextDiv.style.fontSize = "14px";
  67338. this._loadingTextDiv.style.color = "white";
  67339. this._loadingTextDiv.style.textAlign = "center";
  67340. this._loadingTextDiv.innerHTML = "Loading";
  67341. this._loadingDiv.appendChild(this._loadingTextDiv);
  67342. //set the predefined text
  67343. this._loadingTextDiv.innerHTML = this._loadingText;
  67344. // Generating keyframes
  67345. var style = document.createElement('style');
  67346. style.type = 'text/css';
  67347. 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 }";
  67348. style.innerHTML = keyFrames;
  67349. document.getElementsByTagName('head')[0].appendChild(style);
  67350. // Loading img
  67351. var imgBack = new Image();
  67352. 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";
  67353. imgBack.style.position = "absolute";
  67354. imgBack.style.left = "50%";
  67355. imgBack.style.top = "50%";
  67356. imgBack.style.marginLeft = "-60px";
  67357. imgBack.style.marginTop = "-60px";
  67358. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67359. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67360. imgBack.style.transformOrigin = "50% 50%";
  67361. imgBack.style.webkitTransformOrigin = "50% 50%";
  67362. this._loadingDiv.appendChild(imgBack);
  67363. this._resizeLoadingUI();
  67364. window.addEventListener("resize", this._resizeLoadingUI);
  67365. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67366. document.body.appendChild(this._loadingDiv);
  67367. this._loadingDiv.style.opacity = "1";
  67368. };
  67369. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67370. var _this = this;
  67371. if (!this._loadingDiv) {
  67372. return;
  67373. }
  67374. var onTransitionEnd = function () {
  67375. if (!_this._loadingDiv) {
  67376. return;
  67377. }
  67378. document.body.removeChild(_this._loadingDiv);
  67379. window.removeEventListener("resize", _this._resizeLoadingUI);
  67380. _this._loadingDiv = null;
  67381. };
  67382. this._loadingDiv.style.opacity = "0";
  67383. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67384. };
  67385. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67386. set: function (text) {
  67387. this._loadingText = text;
  67388. if (this._loadingTextDiv) {
  67389. this._loadingTextDiv.innerHTML = this._loadingText;
  67390. }
  67391. },
  67392. enumerable: true,
  67393. configurable: true
  67394. });
  67395. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67396. get: function () {
  67397. return this._loadingDivBackgroundColor;
  67398. },
  67399. set: function (color) {
  67400. this._loadingDivBackgroundColor = color;
  67401. if (!this._loadingDiv) {
  67402. return;
  67403. }
  67404. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67405. },
  67406. enumerable: true,
  67407. configurable: true
  67408. });
  67409. return DefaultLoadingScreen;
  67410. }());
  67411. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67412. })(BABYLON || (BABYLON = {}));
  67413. //# sourceMappingURL=babylon.loadingScreen.js.map
  67414. var BABYLON;
  67415. (function (BABYLON) {
  67416. var SceneLoaderProgressEvent = /** @class */ (function () {
  67417. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67418. this.lengthComputable = lengthComputable;
  67419. this.loaded = loaded;
  67420. this.total = total;
  67421. }
  67422. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67423. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67424. };
  67425. return SceneLoaderProgressEvent;
  67426. }());
  67427. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67428. var SceneLoader = /** @class */ (function () {
  67429. function SceneLoader() {
  67430. }
  67431. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67432. get: function () {
  67433. return 0;
  67434. },
  67435. enumerable: true,
  67436. configurable: true
  67437. });
  67438. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67439. get: function () {
  67440. return 1;
  67441. },
  67442. enumerable: true,
  67443. configurable: true
  67444. });
  67445. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67446. get: function () {
  67447. return 2;
  67448. },
  67449. enumerable: true,
  67450. configurable: true
  67451. });
  67452. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67453. get: function () {
  67454. return 3;
  67455. },
  67456. enumerable: true,
  67457. configurable: true
  67458. });
  67459. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67460. get: function () {
  67461. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67462. },
  67463. set: function (value) {
  67464. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67465. },
  67466. enumerable: true,
  67467. configurable: true
  67468. });
  67469. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67470. get: function () {
  67471. return SceneLoader._ShowLoadingScreen;
  67472. },
  67473. set: function (value) {
  67474. SceneLoader._ShowLoadingScreen = value;
  67475. },
  67476. enumerable: true,
  67477. configurable: true
  67478. });
  67479. Object.defineProperty(SceneLoader, "loggingLevel", {
  67480. get: function () {
  67481. return SceneLoader._loggingLevel;
  67482. },
  67483. set: function (value) {
  67484. SceneLoader._loggingLevel = value;
  67485. },
  67486. enumerable: true,
  67487. configurable: true
  67488. });
  67489. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67490. get: function () {
  67491. return SceneLoader._CleanBoneMatrixWeights;
  67492. },
  67493. set: function (value) {
  67494. SceneLoader._CleanBoneMatrixWeights = value;
  67495. },
  67496. enumerable: true,
  67497. configurable: true
  67498. });
  67499. SceneLoader._getDefaultPlugin = function () {
  67500. return SceneLoader._registeredPlugins[".babylon"];
  67501. };
  67502. SceneLoader._getPluginForExtension = function (extension) {
  67503. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67504. if (registeredPlugin) {
  67505. return registeredPlugin;
  67506. }
  67507. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67508. return SceneLoader._getDefaultPlugin();
  67509. };
  67510. SceneLoader._getPluginForDirectLoad = function (data) {
  67511. for (var extension in SceneLoader._registeredPlugins) {
  67512. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67513. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67514. return SceneLoader._registeredPlugins[extension];
  67515. }
  67516. }
  67517. return SceneLoader._getDefaultPlugin();
  67518. };
  67519. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67520. if (sceneFilename.name) {
  67521. sceneFilename = sceneFilename.name;
  67522. }
  67523. var queryStringPosition = sceneFilename.indexOf("?");
  67524. if (queryStringPosition !== -1) {
  67525. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67526. }
  67527. var dotPosition = sceneFilename.lastIndexOf(".");
  67528. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67529. return SceneLoader._getPluginForExtension(extension);
  67530. };
  67531. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67532. SceneLoader._getDirectLoad = function (sceneFilename) {
  67533. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67534. return sceneFilename.substr(5);
  67535. }
  67536. return null;
  67537. };
  67538. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67539. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67540. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67541. var plugin;
  67542. if (registeredPlugin.plugin.createPlugin) {
  67543. plugin = registeredPlugin.plugin.createPlugin();
  67544. }
  67545. else {
  67546. plugin = registeredPlugin.plugin;
  67547. }
  67548. var useArrayBuffer = registeredPlugin.isBinary;
  67549. var database;
  67550. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67551. var dataCallback = function (data, responseURL) {
  67552. if (scene.isDisposed) {
  67553. onError("Scene has been disposed");
  67554. return;
  67555. }
  67556. scene.database = database;
  67557. onSuccess(plugin, data, responseURL);
  67558. };
  67559. var request = null;
  67560. var pluginDisposed = false;
  67561. var onDisposeObservable = plugin.onDisposeObservable;
  67562. if (onDisposeObservable) {
  67563. onDisposeObservable.add(function () {
  67564. pluginDisposed = true;
  67565. if (request) {
  67566. request.abort();
  67567. request = null;
  67568. }
  67569. onDispose();
  67570. });
  67571. }
  67572. var manifestChecked = function () {
  67573. if (pluginDisposed) {
  67574. return;
  67575. }
  67576. var url = rootUrl + sceneFilename;
  67577. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67578. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67579. } : undefined, database, useArrayBuffer, function (request, exception) {
  67580. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67581. });
  67582. };
  67583. if (directLoad) {
  67584. dataCallback(directLoad);
  67585. return plugin;
  67586. }
  67587. if (rootUrl.indexOf("file:") === -1) {
  67588. var engine = scene.getEngine();
  67589. var canUseOfflineSupport = engine.enableOfflineSupport;
  67590. if (canUseOfflineSupport) {
  67591. // Also check for exceptions
  67592. var exceptionFound = false;
  67593. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67594. var regex = _a[_i];
  67595. if (regex.test(rootUrl + sceneFilename)) {
  67596. exceptionFound = true;
  67597. break;
  67598. }
  67599. }
  67600. canUseOfflineSupport = !exceptionFound;
  67601. }
  67602. if (canUseOfflineSupport) {
  67603. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67604. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67605. }
  67606. else {
  67607. manifestChecked();
  67608. }
  67609. }
  67610. // Loading file from disk via input file or drag'n'drop
  67611. else {
  67612. var fileOrString = sceneFilename;
  67613. if (fileOrString.name) { // File
  67614. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67615. }
  67616. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67617. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67618. }
  67619. else {
  67620. onError("Unable to find file named " + sceneFilename);
  67621. }
  67622. }
  67623. return plugin;
  67624. };
  67625. // Public functions
  67626. SceneLoader.GetPluginForExtension = function (extension) {
  67627. return SceneLoader._getPluginForExtension(extension).plugin;
  67628. };
  67629. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67630. return !!SceneLoader._registeredPlugins[extension];
  67631. };
  67632. SceneLoader.RegisterPlugin = function (plugin) {
  67633. if (typeof plugin.extensions === "string") {
  67634. var extension = plugin.extensions;
  67635. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67636. plugin: plugin,
  67637. isBinary: false
  67638. };
  67639. }
  67640. else {
  67641. var extensions = plugin.extensions;
  67642. Object.keys(extensions).forEach(function (extension) {
  67643. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67644. plugin: plugin,
  67645. isBinary: extensions[extension].isBinary
  67646. };
  67647. });
  67648. }
  67649. };
  67650. /**
  67651. * Import meshes into a scene
  67652. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67653. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67654. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67655. * @param scene the instance of BABYLON.Scene to append to
  67656. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67657. * @param onProgress a callback with a progress event for each file being loaded
  67658. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67659. * @param pluginExtension the extension used to determine the plugin
  67660. * @returns The loaded plugin
  67661. */
  67662. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67663. if (sceneFilename === void 0) { sceneFilename = ""; }
  67664. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67665. if (onSuccess === void 0) { onSuccess = null; }
  67666. if (onProgress === void 0) { onProgress = null; }
  67667. if (onError === void 0) { onError = null; }
  67668. if (pluginExtension === void 0) { pluginExtension = null; }
  67669. if (!scene) {
  67670. BABYLON.Tools.Error("No scene available to import mesh to");
  67671. return null;
  67672. }
  67673. if (!sceneFilename) {
  67674. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67675. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67676. }
  67677. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67678. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67679. return null;
  67680. }
  67681. var loadingToken = {};
  67682. scene._addPendingData(loadingToken);
  67683. var disposeHandler = function () {
  67684. scene._removePendingData(loadingToken);
  67685. };
  67686. var errorHandler = function (message, exception) {
  67687. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67688. if (onError) {
  67689. onError(scene, errorMessage, exception);
  67690. }
  67691. else {
  67692. BABYLON.Tools.Error(errorMessage);
  67693. // should the exception be thrown?
  67694. }
  67695. disposeHandler();
  67696. };
  67697. var progressHandler = onProgress ? function (event) {
  67698. try {
  67699. onProgress(event);
  67700. }
  67701. catch (e) {
  67702. errorHandler("Error in onProgress callback", e);
  67703. }
  67704. } : undefined;
  67705. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67706. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67707. if (onSuccess) {
  67708. try {
  67709. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67710. }
  67711. catch (e) {
  67712. errorHandler("Error in onSuccess callback", e);
  67713. }
  67714. }
  67715. scene._removePendingData(loadingToken);
  67716. };
  67717. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67718. if (plugin.rewriteRootURL) {
  67719. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67720. }
  67721. if (sceneFilename === "") {
  67722. if (sceneFilename === "") {
  67723. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67724. }
  67725. }
  67726. if (plugin.importMesh) {
  67727. var syncedPlugin = plugin;
  67728. var meshes = new Array();
  67729. var particleSystems = new Array();
  67730. var skeletons = new Array();
  67731. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67732. return;
  67733. }
  67734. scene.loadingPluginName = plugin.name;
  67735. successHandler(meshes, particleSystems, skeletons, []);
  67736. }
  67737. else {
  67738. var asyncedPlugin = plugin;
  67739. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67740. scene.loadingPluginName = plugin.name;
  67741. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67742. }).catch(function (error) {
  67743. errorHandler(error.message, error);
  67744. });
  67745. }
  67746. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67747. };
  67748. /**
  67749. * Import meshes into a scene
  67750. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67751. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67752. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67753. * @param scene the instance of BABYLON.Scene to append to
  67754. * @param onProgress a callback with a progress event for each file being loaded
  67755. * @param pluginExtension the extension used to determine the plugin
  67756. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67757. */
  67758. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67759. if (sceneFilename === void 0) { sceneFilename = ""; }
  67760. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67761. if (onProgress === void 0) { onProgress = null; }
  67762. if (pluginExtension === void 0) { pluginExtension = null; }
  67763. return new Promise(function (resolve, reject) {
  67764. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67765. resolve({
  67766. meshes: meshes,
  67767. particleSystems: particleSystems,
  67768. skeletons: skeletons,
  67769. animationGroups: animationGroups
  67770. });
  67771. }, onProgress, function (scene, message, exception) {
  67772. reject(exception || new Error(message));
  67773. }, pluginExtension);
  67774. });
  67775. };
  67776. /**
  67777. * Load a scene
  67778. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67779. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67780. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67781. * @param onSuccess a callback with the scene when import succeeds
  67782. * @param onProgress a callback with a progress event for each file being loaded
  67783. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67784. * @param pluginExtension the extension used to determine the plugin
  67785. * @returns The loaded plugin
  67786. */
  67787. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67788. if (onSuccess === void 0) { onSuccess = null; }
  67789. if (onProgress === void 0) { onProgress = null; }
  67790. if (onError === void 0) { onError = null; }
  67791. if (pluginExtension === void 0) { pluginExtension = null; }
  67792. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67793. };
  67794. /**
  67795. * Load a scene
  67796. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67797. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67798. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67799. * @param onProgress a callback with a progress event for each file being loaded
  67800. * @param pluginExtension the extension used to determine the plugin
  67801. * @returns The loaded scene
  67802. */
  67803. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67804. if (onProgress === void 0) { onProgress = null; }
  67805. if (pluginExtension === void 0) { pluginExtension = null; }
  67806. return new Promise(function (resolve, reject) {
  67807. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67808. resolve(scene);
  67809. }, onProgress, function (scene, message, exception) {
  67810. reject(exception || new Error(message));
  67811. }, pluginExtension);
  67812. });
  67813. };
  67814. /**
  67815. * Append a scene
  67816. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67817. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67818. * @param scene is the instance of BABYLON.Scene to append to
  67819. * @param onSuccess a callback with the scene when import succeeds
  67820. * @param onProgress a callback with a progress event for each file being loaded
  67821. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67822. * @param pluginExtension the extension used to determine the plugin
  67823. * @returns The loaded plugin
  67824. */
  67825. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67826. if (sceneFilename === void 0) { sceneFilename = ""; }
  67827. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67828. if (onSuccess === void 0) { onSuccess = null; }
  67829. if (onProgress === void 0) { onProgress = null; }
  67830. if (onError === void 0) { onError = null; }
  67831. if (pluginExtension === void 0) { pluginExtension = null; }
  67832. if (!scene) {
  67833. BABYLON.Tools.Error("No scene available to append to");
  67834. return null;
  67835. }
  67836. if (!sceneFilename) {
  67837. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67838. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67839. }
  67840. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67841. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67842. return null;
  67843. }
  67844. if (SceneLoader.ShowLoadingScreen) {
  67845. scene.getEngine().displayLoadingUI();
  67846. }
  67847. var loadingToken = {};
  67848. scene._addPendingData(loadingToken);
  67849. var disposeHandler = function () {
  67850. scene._removePendingData(loadingToken);
  67851. scene.getEngine().hideLoadingUI();
  67852. };
  67853. var errorHandler = function (message, exception) {
  67854. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67855. if (onError) {
  67856. onError(scene, errorMessage, exception);
  67857. }
  67858. else {
  67859. BABYLON.Tools.Error(errorMessage);
  67860. // should the exception be thrown?
  67861. }
  67862. disposeHandler();
  67863. };
  67864. var progressHandler = onProgress ? function (event) {
  67865. try {
  67866. onProgress(event);
  67867. }
  67868. catch (e) {
  67869. errorHandler("Error in onProgress callback", e);
  67870. }
  67871. } : undefined;
  67872. var successHandler = function () {
  67873. if (onSuccess) {
  67874. try {
  67875. onSuccess(scene);
  67876. }
  67877. catch (e) {
  67878. errorHandler("Error in onSuccess callback", e);
  67879. }
  67880. }
  67881. scene._removePendingData(loadingToken);
  67882. };
  67883. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67884. if (sceneFilename === "") {
  67885. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67886. }
  67887. if (plugin.load) {
  67888. var syncedPlugin = plugin;
  67889. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67890. return;
  67891. }
  67892. scene.loadingPluginName = plugin.name;
  67893. successHandler();
  67894. }
  67895. else {
  67896. var asyncedPlugin = plugin;
  67897. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67898. scene.loadingPluginName = plugin.name;
  67899. successHandler();
  67900. }).catch(function (error) {
  67901. errorHandler(error.message, error);
  67902. });
  67903. }
  67904. if (SceneLoader.ShowLoadingScreen) {
  67905. scene.executeWhenReady(function () {
  67906. scene.getEngine().hideLoadingUI();
  67907. });
  67908. }
  67909. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67910. };
  67911. /**
  67912. * Append a scene
  67913. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67914. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67915. * @param scene is the instance of BABYLON.Scene to append to
  67916. * @param onProgress a callback with a progress event for each file being loaded
  67917. * @param pluginExtension the extension used to determine the plugin
  67918. * @returns The given scene
  67919. */
  67920. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67921. if (sceneFilename === void 0) { sceneFilename = ""; }
  67922. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67923. if (onProgress === void 0) { onProgress = null; }
  67924. if (pluginExtension === void 0) { pluginExtension = null; }
  67925. return new Promise(function (resolve, reject) {
  67926. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67927. resolve(scene);
  67928. }, onProgress, function (scene, message, exception) {
  67929. reject(exception || new Error(message));
  67930. }, pluginExtension);
  67931. });
  67932. };
  67933. /**
  67934. * Load a scene into an asset container
  67935. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67936. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67937. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67938. * @param onSuccess a callback with the scene when import succeeds
  67939. * @param onProgress a callback with a progress event for each file being loaded
  67940. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67941. * @param pluginExtension the extension used to determine the plugin
  67942. * @returns The loaded plugin
  67943. */
  67944. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67945. if (sceneFilename === void 0) { sceneFilename = ""; }
  67946. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67947. if (onSuccess === void 0) { onSuccess = null; }
  67948. if (onProgress === void 0) { onProgress = null; }
  67949. if (onError === void 0) { onError = null; }
  67950. if (pluginExtension === void 0) { pluginExtension = null; }
  67951. if (!scene) {
  67952. BABYLON.Tools.Error("No scene available to load asset container to");
  67953. return null;
  67954. }
  67955. if (!sceneFilename) {
  67956. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67957. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67958. }
  67959. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67960. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67961. return null;
  67962. }
  67963. var loadingToken = {};
  67964. scene._addPendingData(loadingToken);
  67965. var disposeHandler = function () {
  67966. scene._removePendingData(loadingToken);
  67967. };
  67968. var errorHandler = function (message, exception) {
  67969. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67970. if (onError) {
  67971. onError(scene, errorMessage, exception);
  67972. }
  67973. else {
  67974. BABYLON.Tools.Error(errorMessage);
  67975. // should the exception be thrown?
  67976. }
  67977. disposeHandler();
  67978. };
  67979. var progressHandler = onProgress ? function (event) {
  67980. try {
  67981. onProgress(event);
  67982. }
  67983. catch (e) {
  67984. errorHandler("Error in onProgress callback", e);
  67985. }
  67986. } : undefined;
  67987. var successHandler = function (assets) {
  67988. if (onSuccess) {
  67989. try {
  67990. onSuccess(assets);
  67991. }
  67992. catch (e) {
  67993. errorHandler("Error in onSuccess callback", e);
  67994. }
  67995. }
  67996. scene._removePendingData(loadingToken);
  67997. };
  67998. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67999. if (plugin.loadAssetContainer) {
  68000. var syncedPlugin = plugin;
  68001. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68002. if (!assetContainer) {
  68003. return;
  68004. }
  68005. scene.loadingPluginName = plugin.name;
  68006. successHandler(assetContainer);
  68007. }
  68008. else if (plugin.loadAssetContainerAsync) {
  68009. var asyncedPlugin = plugin;
  68010. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68011. scene.loadingPluginName = plugin.name;
  68012. successHandler(assetContainer);
  68013. }).catch(function (error) {
  68014. errorHandler(error.message, error);
  68015. });
  68016. }
  68017. else {
  68018. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68019. }
  68020. if (SceneLoader.ShowLoadingScreen) {
  68021. scene.executeWhenReady(function () {
  68022. scene.getEngine().hideLoadingUI();
  68023. });
  68024. }
  68025. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68026. };
  68027. /**
  68028. * Load a scene into an asset container
  68029. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68030. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68031. * @param scene is the instance of BABYLON.Scene to append to
  68032. * @param onProgress a callback with a progress event for each file being loaded
  68033. * @param pluginExtension the extension used to determine the plugin
  68034. * @returns The loaded asset container
  68035. */
  68036. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68037. if (sceneFilename === void 0) { sceneFilename = ""; }
  68038. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68039. if (onProgress === void 0) { onProgress = null; }
  68040. if (pluginExtension === void 0) { pluginExtension = null; }
  68041. return new Promise(function (resolve, reject) {
  68042. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68043. resolve(assetContainer);
  68044. }, onProgress, function (scene, message, exception) {
  68045. reject(exception || new Error(message));
  68046. }, pluginExtension);
  68047. });
  68048. };
  68049. // Flags
  68050. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68051. SceneLoader._ShowLoadingScreen = true;
  68052. SceneLoader._CleanBoneMatrixWeights = false;
  68053. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68054. // Members
  68055. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68056. SceneLoader._registeredPlugins = {};
  68057. return SceneLoader;
  68058. }());
  68059. BABYLON.SceneLoader = SceneLoader;
  68060. ;
  68061. })(BABYLON || (BABYLON = {}));
  68062. //# sourceMappingURL=babylon.sceneLoader.js.map
  68063. var BABYLON;
  68064. (function (BABYLON) {
  68065. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68066. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68067. var parsedMaterial = parsedData.materials[index];
  68068. if (parsedMaterial.id === id) {
  68069. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68070. }
  68071. }
  68072. return null;
  68073. };
  68074. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68075. for (var i in names) {
  68076. if (mesh.name === names[i]) {
  68077. hierarchyIds.push(mesh.id);
  68078. return true;
  68079. }
  68080. }
  68081. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68082. hierarchyIds.push(mesh.id);
  68083. return true;
  68084. }
  68085. return false;
  68086. };
  68087. var logOperation = function (operation, producer) {
  68088. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68089. };
  68090. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68091. if (addToScene === void 0) { addToScene = false; }
  68092. var container = new BABYLON.AssetContainer(scene);
  68093. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68094. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68095. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68096. // and avoid problems with multiple concurrent .babylon loads.
  68097. var log = "importScene has failed JSON parse";
  68098. try {
  68099. var parsedData = JSON.parse(data);
  68100. log = "";
  68101. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68102. var index;
  68103. var cache;
  68104. // Lights
  68105. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68106. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68107. var parsedLight = parsedData.lights[index];
  68108. var light = BABYLON.Light.Parse(parsedLight, scene);
  68109. if (light) {
  68110. container.lights.push(light);
  68111. log += (index === 0 ? "\n\tLights:" : "");
  68112. log += "\n\t\t" + light.toString(fullDetails);
  68113. }
  68114. }
  68115. }
  68116. // Animations
  68117. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68118. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68119. var parsedAnimation = parsedData.animations[index];
  68120. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68121. scene.animations.push(animation);
  68122. container.animations.push(animation);
  68123. log += (index === 0 ? "\n\tAnimations:" : "");
  68124. log += "\n\t\t" + animation.toString(fullDetails);
  68125. }
  68126. }
  68127. // Materials
  68128. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68129. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68130. var parsedMaterial = parsedData.materials[index];
  68131. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68132. container.materials.push(mat);
  68133. log += (index === 0 ? "\n\tMaterials:" : "");
  68134. log += "\n\t\t" + mat.toString(fullDetails);
  68135. }
  68136. }
  68137. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68138. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68139. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68140. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68141. container.multiMaterials.push(mmat);
  68142. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68143. log += "\n\t\t" + mmat.toString(fullDetails);
  68144. }
  68145. }
  68146. // Morph targets
  68147. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68148. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68149. var managerData = _a[_i];
  68150. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68151. }
  68152. }
  68153. // Skeletons
  68154. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68155. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68156. var parsedSkeleton = parsedData.skeletons[index];
  68157. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68158. container.skeletons.push(skeleton);
  68159. log += (index === 0 ? "\n\tSkeletons:" : "");
  68160. log += "\n\t\t" + skeleton.toString(fullDetails);
  68161. }
  68162. }
  68163. // Geometries
  68164. var geometries = parsedData.geometries;
  68165. if (geometries !== undefined && geometries !== null) {
  68166. var addedGeometry = new Array();
  68167. // Boxes
  68168. var boxes = geometries.boxes;
  68169. if (boxes !== undefined && boxes !== null) {
  68170. for (index = 0, cache = boxes.length; index < cache; index++) {
  68171. var parsedBox = boxes[index];
  68172. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68173. }
  68174. }
  68175. // Spheres
  68176. var spheres = geometries.spheres;
  68177. if (spheres !== undefined && spheres !== null) {
  68178. for (index = 0, cache = spheres.length; index < cache; index++) {
  68179. var parsedSphere = spheres[index];
  68180. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68181. }
  68182. }
  68183. // Cylinders
  68184. var cylinders = geometries.cylinders;
  68185. if (cylinders !== undefined && cylinders !== null) {
  68186. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68187. var parsedCylinder = cylinders[index];
  68188. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68189. }
  68190. }
  68191. // Toruses
  68192. var toruses = geometries.toruses;
  68193. if (toruses !== undefined && toruses !== null) {
  68194. for (index = 0, cache = toruses.length; index < cache; index++) {
  68195. var parsedTorus = toruses[index];
  68196. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68197. }
  68198. }
  68199. // Grounds
  68200. var grounds = geometries.grounds;
  68201. if (grounds !== undefined && grounds !== null) {
  68202. for (index = 0, cache = grounds.length; index < cache; index++) {
  68203. var parsedGround = grounds[index];
  68204. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68205. }
  68206. }
  68207. // Planes
  68208. var planes = geometries.planes;
  68209. if (planes !== undefined && planes !== null) {
  68210. for (index = 0, cache = planes.length; index < cache; index++) {
  68211. var parsedPlane = planes[index];
  68212. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68213. }
  68214. }
  68215. // TorusKnots
  68216. var torusKnots = geometries.torusKnots;
  68217. if (torusKnots !== undefined && torusKnots !== null) {
  68218. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68219. var parsedTorusKnot = torusKnots[index];
  68220. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68221. }
  68222. }
  68223. // VertexData
  68224. var vertexData = geometries.vertexData;
  68225. if (vertexData !== undefined && vertexData !== null) {
  68226. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68227. var parsedVertexData = vertexData[index];
  68228. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68229. }
  68230. }
  68231. addedGeometry.forEach(function (g) {
  68232. if (g) {
  68233. container.geometries.push(g);
  68234. }
  68235. });
  68236. }
  68237. // Transform nodes
  68238. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68239. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68240. var parsedTransformNode = parsedData.transformNodes[index];
  68241. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68242. container.transformNodes.push(node);
  68243. }
  68244. }
  68245. // Meshes
  68246. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68247. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68248. var parsedMesh = parsedData.meshes[index];
  68249. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68250. container.meshes.push(mesh);
  68251. log += (index === 0 ? "\n\tMeshes:" : "");
  68252. log += "\n\t\t" + mesh.toString(fullDetails);
  68253. }
  68254. }
  68255. // Cameras
  68256. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68257. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68258. var parsedCamera = parsedData.cameras[index];
  68259. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68260. container.cameras.push(camera);
  68261. log += (index === 0 ? "\n\tCameras:" : "");
  68262. log += "\n\t\t" + camera.toString(fullDetails);
  68263. }
  68264. }
  68265. // Browsing all the graph to connect the dots
  68266. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68267. var camera = scene.cameras[index];
  68268. if (camera._waitingParentId) {
  68269. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68270. camera._waitingParentId = null;
  68271. }
  68272. }
  68273. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68274. var light_1 = scene.lights[index];
  68275. if (light_1 && light_1._waitingParentId) {
  68276. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68277. light_1._waitingParentId = null;
  68278. }
  68279. }
  68280. // Sounds
  68281. // TODO: add sound
  68282. var loadedSounds = [];
  68283. var loadedSound;
  68284. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68285. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68286. var parsedSound = parsedData.sounds[index];
  68287. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68288. if (!parsedSound.url)
  68289. parsedSound.url = parsedSound.name;
  68290. if (!loadedSounds[parsedSound.url]) {
  68291. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68292. loadedSounds[parsedSound.url] = loadedSound;
  68293. container.sounds.push(loadedSound);
  68294. }
  68295. else {
  68296. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68297. }
  68298. }
  68299. else {
  68300. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68301. }
  68302. }
  68303. }
  68304. loadedSounds = [];
  68305. // Connect parents & children and parse actions
  68306. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68307. var transformNode = scene.transformNodes[index];
  68308. if (transformNode._waitingParentId) {
  68309. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68310. transformNode._waitingParentId = null;
  68311. }
  68312. }
  68313. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68314. var mesh = scene.meshes[index];
  68315. if (mesh._waitingParentId) {
  68316. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68317. mesh._waitingParentId = null;
  68318. }
  68319. if (mesh._waitingActions) {
  68320. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68321. mesh._waitingActions = null;
  68322. }
  68323. }
  68324. // freeze world matrix application
  68325. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68326. var currentMesh = scene.meshes[index];
  68327. if (currentMesh._waitingFreezeWorldMatrix) {
  68328. currentMesh.freezeWorldMatrix();
  68329. currentMesh._waitingFreezeWorldMatrix = null;
  68330. }
  68331. else {
  68332. currentMesh.computeWorldMatrix(true);
  68333. }
  68334. }
  68335. // Particles Systems
  68336. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68337. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68338. var parsedParticleSystem = parsedData.particleSystems[index];
  68339. if (parsedParticleSystem.activeParticleCount) {
  68340. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68341. container.particleSystems.push(ps);
  68342. }
  68343. else {
  68344. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68345. container.particleSystems.push(ps);
  68346. }
  68347. }
  68348. }
  68349. // Shadows
  68350. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68351. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68352. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68353. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68354. // SG would be available on their associated lights
  68355. }
  68356. }
  68357. // Lights exclusions / inclusions
  68358. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68359. var light_2 = scene.lights[index];
  68360. // Excluded check
  68361. if (light_2._excludedMeshesIds.length > 0) {
  68362. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68363. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68364. if (excludedMesh) {
  68365. light_2.excludedMeshes.push(excludedMesh);
  68366. }
  68367. }
  68368. light_2._excludedMeshesIds = [];
  68369. }
  68370. // Included check
  68371. if (light_2._includedOnlyMeshesIds.length > 0) {
  68372. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68373. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68374. if (includedOnlyMesh) {
  68375. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68376. }
  68377. }
  68378. light_2._includedOnlyMeshesIds = [];
  68379. }
  68380. }
  68381. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  68382. // Actions (scene)
  68383. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68384. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68385. }
  68386. if (!addToScene) {
  68387. container.removeAllFromScene();
  68388. }
  68389. }
  68390. catch (err) {
  68391. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68392. if (onError) {
  68393. onError(msg, err);
  68394. }
  68395. else {
  68396. BABYLON.Tools.Log(msg);
  68397. throw err;
  68398. }
  68399. }
  68400. finally {
  68401. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68402. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68403. }
  68404. }
  68405. return container;
  68406. };
  68407. BABYLON.SceneLoader.RegisterPlugin({
  68408. name: "babylon.js",
  68409. extensions: ".babylon",
  68410. canDirectLoad: function (data) {
  68411. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68412. return true;
  68413. }
  68414. return false;
  68415. },
  68416. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68417. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68418. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68419. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68420. // and avoid problems with multiple concurrent .babylon loads.
  68421. var log = "importMesh has failed JSON parse";
  68422. try {
  68423. var parsedData = JSON.parse(data);
  68424. log = "";
  68425. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68426. if (!meshesNames) {
  68427. meshesNames = null;
  68428. }
  68429. else if (!Array.isArray(meshesNames)) {
  68430. meshesNames = [meshesNames];
  68431. }
  68432. var hierarchyIds = new Array();
  68433. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68434. var loadedSkeletonsIds = [];
  68435. var loadedMaterialsIds = [];
  68436. var index;
  68437. var cache;
  68438. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68439. var parsedMesh = parsedData.meshes[index];
  68440. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68441. if (meshesNames !== null) {
  68442. // Remove found mesh name from list.
  68443. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68444. }
  68445. //Geometry?
  68446. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68447. //does the file contain geometries?
  68448. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68449. //find the correct geometry and add it to the scene
  68450. var found = false;
  68451. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68452. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68453. return;
  68454. }
  68455. else {
  68456. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68457. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68458. switch (geometryType) {
  68459. case "boxes":
  68460. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68461. break;
  68462. case "spheres":
  68463. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68464. break;
  68465. case "cylinders":
  68466. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68467. break;
  68468. case "toruses":
  68469. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68470. break;
  68471. case "grounds":
  68472. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68473. break;
  68474. case "planes":
  68475. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68476. break;
  68477. case "torusKnots":
  68478. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68479. break;
  68480. case "vertexData":
  68481. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68482. break;
  68483. }
  68484. found = true;
  68485. }
  68486. });
  68487. }
  68488. });
  68489. if (found === false) {
  68490. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68491. }
  68492. }
  68493. }
  68494. // Material ?
  68495. if (parsedMesh.materialId) {
  68496. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68497. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68498. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68499. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68500. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68501. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68502. var subMatId = parsedMultiMaterial.materials[matIndex];
  68503. loadedMaterialsIds.push(subMatId);
  68504. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68505. if (mat) {
  68506. log += "\n\tMaterial " + mat.toString(fullDetails);
  68507. }
  68508. }
  68509. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68510. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68511. if (mmat) {
  68512. materialFound = true;
  68513. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68514. }
  68515. break;
  68516. }
  68517. }
  68518. }
  68519. if (materialFound === false) {
  68520. loadedMaterialsIds.push(parsedMesh.materialId);
  68521. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68522. if (!mat) {
  68523. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68524. }
  68525. else {
  68526. log += "\n\tMaterial " + mat.toString(fullDetails);
  68527. }
  68528. }
  68529. }
  68530. // Skeleton ?
  68531. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68532. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68533. if (skeletonAlreadyLoaded === false) {
  68534. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68535. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68536. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68537. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68538. skeletons.push(skeleton);
  68539. loadedSkeletonsIds.push(parsedSkeleton.id);
  68540. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68541. }
  68542. }
  68543. }
  68544. }
  68545. // Morph targets ?
  68546. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68547. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68548. var managerData = _a[_i];
  68549. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68550. }
  68551. }
  68552. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68553. meshes.push(mesh);
  68554. log += "\n\tMesh " + mesh.toString(fullDetails);
  68555. }
  68556. }
  68557. // Connecting parents
  68558. var currentMesh;
  68559. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68560. currentMesh = scene.meshes[index];
  68561. if (currentMesh._waitingParentId) {
  68562. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68563. currentMesh._waitingParentId = null;
  68564. }
  68565. }
  68566. // freeze and compute world matrix application
  68567. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68568. currentMesh = scene.meshes[index];
  68569. if (currentMesh._waitingFreezeWorldMatrix) {
  68570. currentMesh.freezeWorldMatrix();
  68571. currentMesh._waitingFreezeWorldMatrix = null;
  68572. }
  68573. else {
  68574. currentMesh.computeWorldMatrix(true);
  68575. }
  68576. }
  68577. }
  68578. // Particles
  68579. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68580. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68581. var parsedParticleSystem = parsedData.particleSystems[index];
  68582. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68583. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68584. }
  68585. }
  68586. }
  68587. return true;
  68588. }
  68589. catch (err) {
  68590. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68591. if (onError) {
  68592. onError(msg, err);
  68593. }
  68594. else {
  68595. BABYLON.Tools.Log(msg);
  68596. throw err;
  68597. }
  68598. }
  68599. finally {
  68600. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68601. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68602. }
  68603. }
  68604. return false;
  68605. },
  68606. load: function (scene, data, rootUrl, onError) {
  68607. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68608. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68609. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68610. // and avoid problems with multiple concurrent .babylon loads.
  68611. var log = "importScene has failed JSON parse";
  68612. try {
  68613. var parsedData = JSON.parse(data);
  68614. log = "";
  68615. // Scene
  68616. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68617. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68618. }
  68619. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68620. scene.autoClear = parsedData.autoClear;
  68621. }
  68622. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68623. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68624. }
  68625. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68626. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68627. }
  68628. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68629. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68630. }
  68631. // Fog
  68632. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68633. scene.fogMode = parsedData.fogMode;
  68634. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68635. scene.fogStart = parsedData.fogStart;
  68636. scene.fogEnd = parsedData.fogEnd;
  68637. scene.fogDensity = parsedData.fogDensity;
  68638. log += "\tFog mode for scene: ";
  68639. switch (scene.fogMode) {
  68640. // getters not compiling, so using hardcoded
  68641. case 1:
  68642. log += "exp\n";
  68643. break;
  68644. case 2:
  68645. log += "exp2\n";
  68646. break;
  68647. case 3:
  68648. log += "linear\n";
  68649. break;
  68650. }
  68651. }
  68652. //Physics
  68653. if (parsedData.physicsEnabled) {
  68654. var physicsPlugin;
  68655. if (parsedData.physicsEngine === "cannon") {
  68656. physicsPlugin = new BABYLON.CannonJSPlugin();
  68657. }
  68658. else if (parsedData.physicsEngine === "oimo") {
  68659. physicsPlugin = new BABYLON.OimoJSPlugin();
  68660. }
  68661. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68662. //else - default engine, which is currently oimo
  68663. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68664. scene.enablePhysics(physicsGravity, physicsPlugin);
  68665. }
  68666. // Metadata
  68667. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68668. scene.metadata = parsedData.metadata;
  68669. }
  68670. //collisions, if defined. otherwise, default is true
  68671. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68672. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68673. }
  68674. scene.workerCollisions = !!parsedData.workerCollisions;
  68675. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68676. if (!container) {
  68677. return false;
  68678. }
  68679. if (parsedData.autoAnimate) {
  68680. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68681. }
  68682. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68683. scene.setActiveCameraByID(parsedData.activeCameraID);
  68684. }
  68685. // Environment texture
  68686. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68687. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68688. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68689. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68690. if (parsedData.environmentTextureRotationY) {
  68691. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68692. }
  68693. scene.environmentTexture = hdrTexture;
  68694. }
  68695. else {
  68696. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68697. if (parsedData.environmentTextureRotationY) {
  68698. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68699. }
  68700. scene.environmentTexture = cubeTexture;
  68701. }
  68702. if (parsedData.createDefaultSkybox === true) {
  68703. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68704. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68705. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68706. }
  68707. }
  68708. // Finish
  68709. return true;
  68710. }
  68711. catch (err) {
  68712. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68713. if (onError) {
  68714. onError(msg, err);
  68715. }
  68716. else {
  68717. BABYLON.Tools.Log(msg);
  68718. throw err;
  68719. }
  68720. }
  68721. finally {
  68722. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68723. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68724. }
  68725. }
  68726. return false;
  68727. },
  68728. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68729. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68730. return container;
  68731. }
  68732. });
  68733. })(BABYLON || (BABYLON = {}));
  68734. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68735. var BABYLON;
  68736. (function (BABYLON) {
  68737. var FilesInput = /** @class */ (function () {
  68738. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68739. this.onProcessFileCallback = function () { return true; };
  68740. this._engine = engine;
  68741. this._currentScene = scene;
  68742. this._sceneLoadedCallback = sceneLoadedCallback;
  68743. this._progressCallback = progressCallback;
  68744. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68745. this._textureLoadingCallback = textureLoadingCallback;
  68746. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68747. this._onReloadCallback = onReloadCallback;
  68748. this._errorCallback = errorCallback;
  68749. }
  68750. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68751. var _this = this;
  68752. if (elementToMonitor) {
  68753. this._elementToMonitor = elementToMonitor;
  68754. this._dragEnterHandler = function (e) { _this.drag(e); };
  68755. this._dragOverHandler = function (e) { _this.drag(e); };
  68756. this._dropHandler = function (e) { _this.drop(e); };
  68757. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68758. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68759. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68760. }
  68761. };
  68762. FilesInput.prototype.dispose = function () {
  68763. if (!this._elementToMonitor) {
  68764. return;
  68765. }
  68766. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68767. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68768. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68769. };
  68770. FilesInput.prototype.renderFunction = function () {
  68771. if (this._additionalRenderLoopLogicCallback) {
  68772. this._additionalRenderLoopLogicCallback();
  68773. }
  68774. if (this._currentScene) {
  68775. if (this._textureLoadingCallback) {
  68776. var remaining = this._currentScene.getWaitingItemsCount();
  68777. if (remaining > 0) {
  68778. this._textureLoadingCallback(remaining);
  68779. }
  68780. }
  68781. this._currentScene.render();
  68782. }
  68783. };
  68784. FilesInput.prototype.drag = function (e) {
  68785. e.stopPropagation();
  68786. e.preventDefault();
  68787. };
  68788. FilesInput.prototype.drop = function (eventDrop) {
  68789. eventDrop.stopPropagation();
  68790. eventDrop.preventDefault();
  68791. this.loadFiles(eventDrop);
  68792. };
  68793. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68794. var _this = this;
  68795. var reader = folder.createReader();
  68796. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68797. reader.readEntries(function (entries) {
  68798. remaining.count += entries.length;
  68799. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68800. var entry = entries_1[_i];
  68801. if (entry.isFile) {
  68802. entry.file(function (file) {
  68803. file.correctName = relativePath + file.name;
  68804. files.push(file);
  68805. if (--remaining.count === 0) {
  68806. callback();
  68807. }
  68808. });
  68809. }
  68810. else if (entry.isDirectory) {
  68811. _this._traverseFolder(entry, files, remaining, callback);
  68812. }
  68813. }
  68814. if (--remaining.count) {
  68815. callback();
  68816. }
  68817. });
  68818. };
  68819. FilesInput.prototype._processFiles = function (files) {
  68820. for (var i = 0; i < files.length; i++) {
  68821. var name = files[i].correctName.toLowerCase();
  68822. var extension = name.split('.').pop();
  68823. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68824. continue;
  68825. }
  68826. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68827. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68828. this._sceneFileToLoad = files[i];
  68829. }
  68830. else {
  68831. FilesInput.FilesToLoad[name] = files[i];
  68832. }
  68833. }
  68834. };
  68835. FilesInput.prototype.loadFiles = function (event) {
  68836. var _this = this;
  68837. if (this._startingProcessingFilesCallback)
  68838. this._startingProcessingFilesCallback();
  68839. // Handling data transfer via drag'n'drop
  68840. if (event && event.dataTransfer && event.dataTransfer.files) {
  68841. this._filesToLoad = event.dataTransfer.files;
  68842. }
  68843. // Handling files from input files
  68844. if (event && event.target && event.target.files) {
  68845. this._filesToLoad = event.target.files;
  68846. }
  68847. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68848. var files_1 = new Array();
  68849. var folders = [];
  68850. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68851. for (var i = 0; i < this._filesToLoad.length; i++) {
  68852. var fileToLoad = this._filesToLoad[i];
  68853. var name_1 = fileToLoad.name.toLowerCase();
  68854. var entry = void 0;
  68855. fileToLoad.correctName = name_1;
  68856. if (items) {
  68857. var item = items[i];
  68858. if (item.getAsEntry) {
  68859. entry = item.getAsEntry();
  68860. }
  68861. else if (item.webkitGetAsEntry) {
  68862. entry = item.webkitGetAsEntry();
  68863. }
  68864. }
  68865. if (!entry) {
  68866. files_1.push(fileToLoad);
  68867. }
  68868. else {
  68869. if (entry.isDirectory) {
  68870. folders.push(entry);
  68871. }
  68872. else {
  68873. files_1.push(fileToLoad);
  68874. }
  68875. }
  68876. }
  68877. if (folders.length === 0) {
  68878. this._processFiles(files_1);
  68879. this._processReload();
  68880. }
  68881. else {
  68882. var remaining = { count: folders.length };
  68883. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68884. var folder = folders_1[_i];
  68885. this._traverseFolder(folder, files_1, remaining, function () {
  68886. _this._processFiles(files_1);
  68887. if (remaining.count === 0) {
  68888. _this._processReload();
  68889. }
  68890. });
  68891. }
  68892. }
  68893. }
  68894. };
  68895. FilesInput.prototype._processReload = function () {
  68896. if (this._onReloadCallback) {
  68897. this._onReloadCallback(this._sceneFileToLoad);
  68898. }
  68899. else {
  68900. this.reload();
  68901. }
  68902. };
  68903. FilesInput.prototype.reload = function () {
  68904. var _this = this;
  68905. // If a scene file has been provided
  68906. if (this._sceneFileToLoad) {
  68907. if (this._currentScene) {
  68908. if (BABYLON.Tools.errorsCount > 0) {
  68909. BABYLON.Tools.ClearLogCache();
  68910. }
  68911. this._engine.stopRenderLoop();
  68912. }
  68913. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68914. if (_this._progressCallback) {
  68915. _this._progressCallback(progress);
  68916. }
  68917. }).then(function (scene) {
  68918. if (_this._currentScene) {
  68919. _this._currentScene.dispose();
  68920. }
  68921. _this._currentScene = scene;
  68922. if (_this._sceneLoadedCallback) {
  68923. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68924. }
  68925. // Wait for textures and shaders to be ready
  68926. _this._currentScene.executeWhenReady(function () {
  68927. _this._engine.runRenderLoop(function () {
  68928. _this.renderFunction();
  68929. });
  68930. });
  68931. }).catch(function (error) {
  68932. if (_this._errorCallback) {
  68933. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68934. }
  68935. });
  68936. }
  68937. else {
  68938. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68939. }
  68940. };
  68941. FilesInput.FilesToLoad = {};
  68942. return FilesInput;
  68943. }());
  68944. BABYLON.FilesInput = FilesInput;
  68945. })(BABYLON || (BABYLON = {}));
  68946. //# sourceMappingURL=babylon.filesInput.js.map
  68947. var BABYLON;
  68948. (function (BABYLON) {
  68949. /**
  68950. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68951. * The underlying implementation relies on an associative array to ensure the best performances.
  68952. * The value can be anything including 'null' but except 'undefined'
  68953. */
  68954. var StringDictionary = /** @class */ (function () {
  68955. function StringDictionary() {
  68956. this._count = 0;
  68957. this._data = {};
  68958. }
  68959. /**
  68960. * This will clear this dictionary and copy the content from the 'source' one.
  68961. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68962. * @param source the dictionary to take the content from and copy to this dictionary
  68963. */
  68964. StringDictionary.prototype.copyFrom = function (source) {
  68965. var _this = this;
  68966. this.clear();
  68967. source.forEach(function (t, v) { return _this.add(t, v); });
  68968. };
  68969. /**
  68970. * Get a value based from its key
  68971. * @param key the given key to get the matching value from
  68972. * @return the value if found, otherwise undefined is returned
  68973. */
  68974. StringDictionary.prototype.get = function (key) {
  68975. var val = this._data[key];
  68976. if (val !== undefined) {
  68977. return val;
  68978. }
  68979. return undefined;
  68980. };
  68981. /**
  68982. * Get a value from its key or add it if it doesn't exist.
  68983. * This method will ensure you that a given key/data will be present in the dictionary.
  68984. * @param key the given key to get the matching value from
  68985. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68986. * The factory will only be invoked if there's no data for the given key.
  68987. * @return the value corresponding to the key.
  68988. */
  68989. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68990. var val = this.get(key);
  68991. if (val !== undefined) {
  68992. return val;
  68993. }
  68994. val = factory(key);
  68995. if (val) {
  68996. this.add(key, val);
  68997. }
  68998. return val;
  68999. };
  69000. /**
  69001. * Get a value from its key if present in the dictionary otherwise add it
  69002. * @param key the key to get the value from
  69003. * @param val if there's no such key/value pair in the dictionary add it with this value
  69004. * @return the value corresponding to the key
  69005. */
  69006. StringDictionary.prototype.getOrAdd = function (key, val) {
  69007. var curVal = this.get(key);
  69008. if (curVal !== undefined) {
  69009. return curVal;
  69010. }
  69011. this.add(key, val);
  69012. return val;
  69013. };
  69014. /**
  69015. * Check if there's a given key in the dictionary
  69016. * @param key the key to check for
  69017. * @return true if the key is present, false otherwise
  69018. */
  69019. StringDictionary.prototype.contains = function (key) {
  69020. return this._data[key] !== undefined;
  69021. };
  69022. /**
  69023. * Add a new key and its corresponding value
  69024. * @param key the key to add
  69025. * @param value the value corresponding to the key
  69026. * @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
  69027. */
  69028. StringDictionary.prototype.add = function (key, value) {
  69029. if (this._data[key] !== undefined) {
  69030. return false;
  69031. }
  69032. this._data[key] = value;
  69033. ++this._count;
  69034. return true;
  69035. };
  69036. StringDictionary.prototype.set = function (key, value) {
  69037. if (this._data[key] === undefined) {
  69038. return false;
  69039. }
  69040. this._data[key] = value;
  69041. return true;
  69042. };
  69043. /**
  69044. * Get the element of the given key and remove it from the dictionary
  69045. * @param key
  69046. */
  69047. StringDictionary.prototype.getAndRemove = function (key) {
  69048. var val = this.get(key);
  69049. if (val !== undefined) {
  69050. delete this._data[key];
  69051. --this._count;
  69052. return val;
  69053. }
  69054. return null;
  69055. };
  69056. /**
  69057. * Remove a key/value from the dictionary.
  69058. * @param key the key to remove
  69059. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69060. */
  69061. StringDictionary.prototype.remove = function (key) {
  69062. if (this.contains(key)) {
  69063. delete this._data[key];
  69064. --this._count;
  69065. return true;
  69066. }
  69067. return false;
  69068. };
  69069. /**
  69070. * Clear the whole content of the dictionary
  69071. */
  69072. StringDictionary.prototype.clear = function () {
  69073. this._data = {};
  69074. this._count = 0;
  69075. };
  69076. Object.defineProperty(StringDictionary.prototype, "count", {
  69077. get: function () {
  69078. return this._count;
  69079. },
  69080. enumerable: true,
  69081. configurable: true
  69082. });
  69083. /**
  69084. * Execute a callback on each key/val of the dictionary.
  69085. * Note that you can remove any element in this dictionary in the callback implementation
  69086. * @param callback the callback to execute on a given key/value pair
  69087. */
  69088. StringDictionary.prototype.forEach = function (callback) {
  69089. for (var cur in this._data) {
  69090. var val = this._data[cur];
  69091. callback(cur, val);
  69092. }
  69093. };
  69094. /**
  69095. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69096. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69097. * Note that you can remove any element in this dictionary in the callback implementation
  69098. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69099. */
  69100. StringDictionary.prototype.first = function (callback) {
  69101. for (var cur in this._data) {
  69102. var val = this._data[cur];
  69103. var res = callback(cur, val);
  69104. if (res) {
  69105. return res;
  69106. }
  69107. }
  69108. return null;
  69109. };
  69110. return StringDictionary;
  69111. }());
  69112. BABYLON.StringDictionary = StringDictionary;
  69113. })(BABYLON || (BABYLON = {}));
  69114. //# sourceMappingURL=babylon.stringDictionary.js.map
  69115. var BABYLON;
  69116. (function (BABYLON) {
  69117. var Tags = /** @class */ (function () {
  69118. function Tags() {
  69119. }
  69120. Tags.EnableFor = function (obj) {
  69121. obj._tags = obj._tags || {};
  69122. obj.hasTags = function () {
  69123. return Tags.HasTags(obj);
  69124. };
  69125. obj.addTags = function (tagsString) {
  69126. return Tags.AddTagsTo(obj, tagsString);
  69127. };
  69128. obj.removeTags = function (tagsString) {
  69129. return Tags.RemoveTagsFrom(obj, tagsString);
  69130. };
  69131. obj.matchesTagsQuery = function (tagsQuery) {
  69132. return Tags.MatchesQuery(obj, tagsQuery);
  69133. };
  69134. };
  69135. Tags.DisableFor = function (obj) {
  69136. delete obj._tags;
  69137. delete obj.hasTags;
  69138. delete obj.addTags;
  69139. delete obj.removeTags;
  69140. delete obj.matchesTagsQuery;
  69141. };
  69142. Tags.HasTags = function (obj) {
  69143. if (!obj._tags) {
  69144. return false;
  69145. }
  69146. return !BABYLON.Tools.IsEmpty(obj._tags);
  69147. };
  69148. Tags.GetTags = function (obj, asString) {
  69149. if (asString === void 0) { asString = true; }
  69150. if (!obj._tags) {
  69151. return null;
  69152. }
  69153. if (asString) {
  69154. var tagsArray = [];
  69155. for (var tag in obj._tags) {
  69156. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69157. tagsArray.push(tag);
  69158. }
  69159. }
  69160. return tagsArray.join(" ");
  69161. }
  69162. else {
  69163. return obj._tags;
  69164. }
  69165. };
  69166. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69167. // a tag cannot start with '||', '&&', and '!'
  69168. // it cannot contain whitespaces
  69169. Tags.AddTagsTo = function (obj, tagsString) {
  69170. if (!tagsString) {
  69171. return;
  69172. }
  69173. if (typeof tagsString !== "string") {
  69174. return;
  69175. }
  69176. var tags = tagsString.split(" ");
  69177. tags.forEach(function (tag, index, array) {
  69178. Tags._AddTagTo(obj, tag);
  69179. });
  69180. };
  69181. Tags._AddTagTo = function (obj, tag) {
  69182. tag = tag.trim();
  69183. if (tag === "" || tag === "true" || tag === "false") {
  69184. return;
  69185. }
  69186. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69187. return;
  69188. }
  69189. Tags.EnableFor(obj);
  69190. obj._tags[tag] = true;
  69191. };
  69192. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69193. if (!Tags.HasTags(obj)) {
  69194. return;
  69195. }
  69196. var tags = tagsString.split(" ");
  69197. for (var t in tags) {
  69198. Tags._RemoveTagFrom(obj, tags[t]);
  69199. }
  69200. };
  69201. Tags._RemoveTagFrom = function (obj, tag) {
  69202. delete obj._tags[tag];
  69203. };
  69204. Tags.MatchesQuery = function (obj, tagsQuery) {
  69205. if (tagsQuery === undefined) {
  69206. return true;
  69207. }
  69208. if (tagsQuery === "") {
  69209. return Tags.HasTags(obj);
  69210. }
  69211. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69212. };
  69213. return Tags;
  69214. }());
  69215. BABYLON.Tags = Tags;
  69216. })(BABYLON || (BABYLON = {}));
  69217. //# sourceMappingURL=babylon.tags.js.map
  69218. var BABYLON;
  69219. (function (BABYLON) {
  69220. /**
  69221. * Class used to evalaute queries containing `and` and `or` operators
  69222. */
  69223. var AndOrNotEvaluator = /** @class */ (function () {
  69224. function AndOrNotEvaluator() {
  69225. }
  69226. /**
  69227. * Evaluate a query
  69228. * @param query defines the query to evaluate
  69229. * @param evaluateCallback defines the callback used to filter result
  69230. * @returns true if the query matches
  69231. */
  69232. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69233. if (!query.match(/\([^\(\)]*\)/g)) {
  69234. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69235. }
  69236. else {
  69237. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69238. // remove parenthesis
  69239. r = r.slice(1, r.length - 1);
  69240. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69241. });
  69242. }
  69243. if (query === "true") {
  69244. return true;
  69245. }
  69246. if (query === "false") {
  69247. return false;
  69248. }
  69249. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69250. };
  69251. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69252. evaluateCallback = evaluateCallback || (function (r) {
  69253. return r === "true" ? true : false;
  69254. });
  69255. var result;
  69256. var or = parenthesisContent.split("||");
  69257. for (var i in or) {
  69258. if (or.hasOwnProperty(i)) {
  69259. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69260. var and = ori.split("&&");
  69261. if (and.length > 1) {
  69262. for (var j = 0; j < and.length; ++j) {
  69263. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69264. if (andj !== "true" && andj !== "false") {
  69265. if (andj[0] === "!") {
  69266. result = !evaluateCallback(andj.substring(1));
  69267. }
  69268. else {
  69269. result = evaluateCallback(andj);
  69270. }
  69271. }
  69272. else {
  69273. result = andj === "true" ? true : false;
  69274. }
  69275. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69276. ori = "false";
  69277. break;
  69278. }
  69279. }
  69280. }
  69281. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69282. result = true;
  69283. break;
  69284. }
  69285. // result equals false (or undefined)
  69286. if (ori !== "true" && ori !== "false") {
  69287. if (ori[0] === "!") {
  69288. result = !evaluateCallback(ori.substring(1));
  69289. }
  69290. else {
  69291. result = evaluateCallback(ori);
  69292. }
  69293. }
  69294. else {
  69295. result = ori === "true" ? true : false;
  69296. }
  69297. }
  69298. }
  69299. // the whole parenthesis scope is replaced by 'true' or 'false'
  69300. return result ? "true" : "false";
  69301. };
  69302. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69303. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69304. // remove whitespaces
  69305. r = r.replace(/[\s]/g, function () { return ""; });
  69306. return r.length % 2 ? "!" : "";
  69307. });
  69308. booleanString = booleanString.trim();
  69309. if (booleanString === "!true") {
  69310. booleanString = "false";
  69311. }
  69312. else if (booleanString === "!false") {
  69313. booleanString = "true";
  69314. }
  69315. return booleanString;
  69316. };
  69317. return AndOrNotEvaluator;
  69318. }());
  69319. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69320. })(BABYLON || (BABYLON = {}));
  69321. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69322. var BABYLON;
  69323. (function (BABYLON) {
  69324. /**
  69325. * Class used to enable access to IndexedDB
  69326. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69327. */
  69328. var Database = /** @class */ (function () {
  69329. /**
  69330. * Creates a new Database
  69331. * @param urlToScene defines the url to load the scene
  69332. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69333. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69334. */
  69335. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69336. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69337. var _this = this;
  69338. // Handling various flavors of prefixed version of IndexedDB
  69339. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69340. this.callbackManifestChecked = callbackManifestChecked;
  69341. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69342. this.db = null;
  69343. this._enableSceneOffline = false;
  69344. this._enableTexturesOffline = false;
  69345. this.manifestVersionFound = 0;
  69346. this.mustUpdateRessources = false;
  69347. this.hasReachedQuota = false;
  69348. if (!Database.IDBStorageEnabled) {
  69349. this.callbackManifestChecked(true);
  69350. }
  69351. else {
  69352. if (disableManifestCheck) {
  69353. this._enableSceneOffline = true;
  69354. this._enableTexturesOffline = true;
  69355. this.manifestVersionFound = 1;
  69356. BABYLON.Tools.SetImmediate(function () {
  69357. _this.callbackManifestChecked(true);
  69358. });
  69359. }
  69360. else {
  69361. this._checkManifestFile();
  69362. }
  69363. }
  69364. }
  69365. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69366. /**
  69367. * Gets a boolean indicating if scene must be saved in the database
  69368. */
  69369. get: function () {
  69370. return this._enableSceneOffline;
  69371. },
  69372. enumerable: true,
  69373. configurable: true
  69374. });
  69375. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69376. /**
  69377. * Gets a boolean indicating if textures must be saved in the database
  69378. */
  69379. get: function () {
  69380. return this._enableTexturesOffline;
  69381. },
  69382. enumerable: true,
  69383. configurable: true
  69384. });
  69385. Database.prototype._checkManifestFile = function () {
  69386. var _this = this;
  69387. var noManifestFile = function () {
  69388. _this._enableSceneOffline = false;
  69389. _this._enableTexturesOffline = false;
  69390. _this.callbackManifestChecked(false);
  69391. };
  69392. var timeStampUsed = false;
  69393. var manifestURL = this.currentSceneUrl + ".manifest";
  69394. var xhr = new XMLHttpRequest();
  69395. if (navigator.onLine) {
  69396. // Adding a timestamp to by-pass browsers' cache
  69397. timeStampUsed = true;
  69398. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69399. }
  69400. xhr.open("GET", manifestURL, true);
  69401. xhr.addEventListener("load", function () {
  69402. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69403. try {
  69404. var manifestFile = JSON.parse(xhr.response);
  69405. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69406. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69407. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69408. _this.manifestVersionFound = manifestFile.version;
  69409. }
  69410. if (_this.callbackManifestChecked) {
  69411. _this.callbackManifestChecked(true);
  69412. }
  69413. }
  69414. catch (ex) {
  69415. noManifestFile();
  69416. }
  69417. }
  69418. else {
  69419. noManifestFile();
  69420. }
  69421. }, false);
  69422. xhr.addEventListener("error", function (event) {
  69423. if (timeStampUsed) {
  69424. timeStampUsed = false;
  69425. // Let's retry without the timeStamp
  69426. // It could fail when coupled with HTML5 Offline API
  69427. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69428. xhr.open("GET", retryManifestURL, true);
  69429. xhr.send();
  69430. }
  69431. else {
  69432. noManifestFile();
  69433. }
  69434. }, false);
  69435. try {
  69436. xhr.send();
  69437. }
  69438. catch (ex) {
  69439. BABYLON.Tools.Error("Error on XHR send request.");
  69440. this.callbackManifestChecked(false);
  69441. }
  69442. };
  69443. /**
  69444. * Open the database and make it available
  69445. * @param successCallback defines the callback to call on success
  69446. * @param errorCallback defines the callback to call on error
  69447. */
  69448. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69449. var _this = this;
  69450. var handleError = function () {
  69451. _this.isSupported = false;
  69452. if (errorCallback)
  69453. errorCallback();
  69454. };
  69455. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69456. // Your browser doesn't support IndexedDB
  69457. this.isSupported = false;
  69458. if (errorCallback)
  69459. errorCallback();
  69460. }
  69461. else {
  69462. // If the DB hasn't been opened or created yet
  69463. if (!this.db) {
  69464. this.hasReachedQuota = false;
  69465. this.isSupported = true;
  69466. var request = this.idbFactory.open("babylonjs", 1);
  69467. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69468. request.onerror = function (event) {
  69469. handleError();
  69470. };
  69471. // executes when a version change transaction cannot complete due to other active transactions
  69472. request.onblocked = function (event) {
  69473. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69474. handleError();
  69475. };
  69476. // DB has been opened successfully
  69477. request.onsuccess = function (event) {
  69478. _this.db = request.result;
  69479. successCallback();
  69480. };
  69481. // Initialization of the DB. Creating Scenes & Textures stores
  69482. request.onupgradeneeded = function (event) {
  69483. _this.db = (event.target).result;
  69484. if (_this.db) {
  69485. try {
  69486. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69487. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69488. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69489. }
  69490. catch (ex) {
  69491. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69492. handleError();
  69493. }
  69494. }
  69495. };
  69496. }
  69497. // DB has already been created and opened
  69498. else {
  69499. if (successCallback)
  69500. successCallback();
  69501. }
  69502. }
  69503. };
  69504. /**
  69505. * Loads an image from the database
  69506. * @param url defines the url to load from
  69507. * @param image defines the target DOM image
  69508. */
  69509. Database.prototype.loadImageFromDB = function (url, image) {
  69510. var _this = this;
  69511. var completeURL = Database._ReturnFullUrlLocation(url);
  69512. var saveAndLoadImage = function () {
  69513. if (!_this.hasReachedQuota && _this.db !== null) {
  69514. // the texture is not yet in the DB, let's try to save it
  69515. _this._saveImageIntoDBAsync(completeURL, image);
  69516. }
  69517. // If the texture is not in the DB and we've reached the DB quota limit
  69518. // let's load it directly from the web
  69519. else {
  69520. image.src = url;
  69521. }
  69522. };
  69523. if (!this.mustUpdateRessources) {
  69524. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69525. }
  69526. // First time we're download the images or update requested in the manifest file by a version change
  69527. else {
  69528. saveAndLoadImage();
  69529. }
  69530. };
  69531. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69532. if (this.isSupported && this.db !== null) {
  69533. var texture;
  69534. var transaction = this.db.transaction(["textures"]);
  69535. transaction.onabort = function (event) {
  69536. image.src = url;
  69537. };
  69538. transaction.oncomplete = function (event) {
  69539. var blobTextureURL;
  69540. if (texture) {
  69541. var URL = window.URL || window.webkitURL;
  69542. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69543. image.onerror = function () {
  69544. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69545. image.src = url;
  69546. };
  69547. image.src = blobTextureURL;
  69548. }
  69549. else {
  69550. notInDBCallback();
  69551. }
  69552. };
  69553. var getRequest = transaction.objectStore("textures").get(url);
  69554. getRequest.onsuccess = function (event) {
  69555. texture = (event.target).result;
  69556. };
  69557. getRequest.onerror = function (event) {
  69558. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69559. image.src = url;
  69560. };
  69561. }
  69562. else {
  69563. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69564. image.src = url;
  69565. }
  69566. };
  69567. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69568. var _this = this;
  69569. if (this.isSupported) {
  69570. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69571. var generateBlobUrl = function () {
  69572. var blobTextureURL;
  69573. if (blob) {
  69574. var URL = window.URL || window.webkitURL;
  69575. try {
  69576. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69577. }
  69578. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69579. catch (ex) {
  69580. blobTextureURL = URL.createObjectURL(blob);
  69581. }
  69582. }
  69583. if (blobTextureURL) {
  69584. image.src = blobTextureURL;
  69585. }
  69586. };
  69587. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69588. var xhr = new XMLHttpRequest(), blob;
  69589. xhr.open("GET", url, true);
  69590. xhr.responseType = "blob";
  69591. xhr.addEventListener("load", function () {
  69592. if (xhr.status === 200 && _this.db) {
  69593. // Blob as response (XHR2)
  69594. blob = xhr.response;
  69595. var transaction = _this.db.transaction(["textures"], "readwrite");
  69596. // the transaction could abort because of a QuotaExceededError error
  69597. transaction.onabort = function (event) {
  69598. try {
  69599. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69600. var srcElement = (event.srcElement || event.target);
  69601. var error = srcElement.error;
  69602. if (error && error.name === "QuotaExceededError") {
  69603. _this.hasReachedQuota = true;
  69604. }
  69605. }
  69606. catch (ex) { }
  69607. generateBlobUrl();
  69608. };
  69609. transaction.oncomplete = function (event) {
  69610. generateBlobUrl();
  69611. };
  69612. var newTexture = { textureUrl: url, data: blob };
  69613. try {
  69614. // Put the blob into the dabase
  69615. var addRequest = transaction.objectStore("textures").put(newTexture);
  69616. addRequest.onsuccess = function (event) {
  69617. };
  69618. addRequest.onerror = function (event) {
  69619. generateBlobUrl();
  69620. };
  69621. }
  69622. catch (ex) {
  69623. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69624. if (ex.code === 25) {
  69625. Database.IsUASupportingBlobStorage = false;
  69626. }
  69627. image.src = url;
  69628. }
  69629. }
  69630. else {
  69631. image.src = url;
  69632. }
  69633. }, false);
  69634. xhr.addEventListener("error", function (event) {
  69635. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69636. image.src = url;
  69637. }, false);
  69638. xhr.send();
  69639. }
  69640. else {
  69641. image.src = url;
  69642. }
  69643. }
  69644. else {
  69645. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69646. image.src = url;
  69647. }
  69648. };
  69649. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69650. var _this = this;
  69651. var updateVersion = function () {
  69652. // the version is not yet in the DB or we need to update it
  69653. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69654. };
  69655. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69656. };
  69657. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69658. var _this = this;
  69659. if (this.isSupported && this.db) {
  69660. var version;
  69661. try {
  69662. var transaction = this.db.transaction(["versions"]);
  69663. transaction.oncomplete = function (event) {
  69664. if (version) {
  69665. // If the version in the JSON file is different from the version in DB
  69666. if (_this.manifestVersionFound !== version.data) {
  69667. _this.mustUpdateRessources = true;
  69668. updateInDBCallback();
  69669. }
  69670. else {
  69671. callback(version.data);
  69672. }
  69673. }
  69674. // version was not found in DB
  69675. else {
  69676. _this.mustUpdateRessources = true;
  69677. updateInDBCallback();
  69678. }
  69679. };
  69680. transaction.onabort = function (event) {
  69681. callback(-1);
  69682. };
  69683. var getRequest = transaction.objectStore("versions").get(url);
  69684. getRequest.onsuccess = function (event) {
  69685. version = (event.target).result;
  69686. };
  69687. getRequest.onerror = function (event) {
  69688. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69689. callback(-1);
  69690. };
  69691. }
  69692. catch (ex) {
  69693. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69694. callback(-1);
  69695. }
  69696. }
  69697. else {
  69698. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69699. callback(-1);
  69700. }
  69701. };
  69702. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69703. var _this = this;
  69704. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69705. try {
  69706. // Open a transaction to the database
  69707. var transaction = this.db.transaction(["versions"], "readwrite");
  69708. // the transaction could abort because of a QuotaExceededError error
  69709. transaction.onabort = function (event) {
  69710. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69711. var error = event.srcElement['error'];
  69712. if (error && error.name === "QuotaExceededError") {
  69713. _this.hasReachedQuota = true;
  69714. }
  69715. }
  69716. catch (ex) { }
  69717. callback(-1);
  69718. };
  69719. transaction.oncomplete = function (event) {
  69720. callback(_this.manifestVersionFound);
  69721. };
  69722. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69723. // Put the scene into the database
  69724. var addRequest = transaction.objectStore("versions").put(newVersion);
  69725. addRequest.onsuccess = function (event) {
  69726. };
  69727. addRequest.onerror = function (event) {
  69728. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69729. };
  69730. }
  69731. catch (ex) {
  69732. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69733. callback(-1);
  69734. }
  69735. }
  69736. else {
  69737. callback(-1);
  69738. }
  69739. };
  69740. /**
  69741. * Loads a file from database
  69742. * @param url defines the URL to load from
  69743. * @param sceneLoaded defines a callback to call on success
  69744. * @param progressCallBack defines a callback to call when progress changed
  69745. * @param errorCallback defines a callback to call on error
  69746. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69747. */
  69748. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69749. var _this = this;
  69750. var completeUrl = Database._ReturnFullUrlLocation(url);
  69751. var saveAndLoadFile = function () {
  69752. // the scene is not yet in the DB, let's try to save it
  69753. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69754. };
  69755. this._checkVersionFromDB(completeUrl, function (version) {
  69756. if (version !== -1) {
  69757. if (!_this.mustUpdateRessources) {
  69758. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69759. }
  69760. else {
  69761. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69762. }
  69763. }
  69764. else {
  69765. if (errorCallback) {
  69766. errorCallback();
  69767. }
  69768. }
  69769. });
  69770. };
  69771. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69772. if (this.isSupported && this.db) {
  69773. var targetStore;
  69774. if (url.indexOf(".babylon") !== -1) {
  69775. targetStore = "scenes";
  69776. }
  69777. else {
  69778. targetStore = "textures";
  69779. }
  69780. var file;
  69781. var transaction = this.db.transaction([targetStore]);
  69782. transaction.oncomplete = function (event) {
  69783. if (file) {
  69784. callback(file.data);
  69785. }
  69786. // file was not found in DB
  69787. else {
  69788. notInDBCallback();
  69789. }
  69790. };
  69791. transaction.onabort = function (event) {
  69792. notInDBCallback();
  69793. };
  69794. var getRequest = transaction.objectStore(targetStore).get(url);
  69795. getRequest.onsuccess = function (event) {
  69796. file = (event.target).result;
  69797. };
  69798. getRequest.onerror = function (event) {
  69799. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69800. notInDBCallback();
  69801. };
  69802. }
  69803. else {
  69804. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69805. callback();
  69806. }
  69807. };
  69808. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69809. var _this = this;
  69810. if (this.isSupported) {
  69811. var targetStore;
  69812. if (url.indexOf(".babylon") !== -1) {
  69813. targetStore = "scenes";
  69814. }
  69815. else {
  69816. targetStore = "textures";
  69817. }
  69818. // Create XHR
  69819. var xhr = new XMLHttpRequest();
  69820. var fileData;
  69821. xhr.open("GET", url, true);
  69822. if (useArrayBuffer) {
  69823. xhr.responseType = "arraybuffer";
  69824. }
  69825. if (progressCallback) {
  69826. xhr.onprogress = progressCallback;
  69827. }
  69828. xhr.addEventListener("load", function () {
  69829. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69830. // Blob as response (XHR2)
  69831. //fileData = xhr.responseText;
  69832. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69833. if (!_this.hasReachedQuota && _this.db) {
  69834. // Open a transaction to the database
  69835. var transaction = _this.db.transaction([targetStore], "readwrite");
  69836. // the transaction could abort because of a QuotaExceededError error
  69837. transaction.onabort = function (event) {
  69838. try {
  69839. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69840. var error = event.srcElement['error'];
  69841. if (error && error.name === "QuotaExceededError") {
  69842. _this.hasReachedQuota = true;
  69843. }
  69844. }
  69845. catch (ex) { }
  69846. callback(fileData);
  69847. };
  69848. transaction.oncomplete = function (event) {
  69849. callback(fileData);
  69850. };
  69851. var newFile;
  69852. if (targetStore === "scenes") {
  69853. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69854. }
  69855. else {
  69856. newFile = { textureUrl: url, data: fileData };
  69857. }
  69858. try {
  69859. // Put the scene into the database
  69860. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69861. addRequest.onsuccess = function (event) {
  69862. };
  69863. addRequest.onerror = function (event) {
  69864. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69865. };
  69866. }
  69867. catch (ex) {
  69868. callback(fileData);
  69869. }
  69870. }
  69871. else {
  69872. callback(fileData);
  69873. }
  69874. }
  69875. else {
  69876. callback();
  69877. }
  69878. }, false);
  69879. xhr.addEventListener("error", function (event) {
  69880. BABYLON.Tools.Error("error on XHR request.");
  69881. callback();
  69882. }, false);
  69883. xhr.send();
  69884. }
  69885. else {
  69886. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69887. callback();
  69888. }
  69889. };
  69890. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69891. Database.IsUASupportingBlobStorage = true;
  69892. /** Gets a boolean indicating if Database storate is enabled */
  69893. Database.IDBStorageEnabled = true;
  69894. Database._ParseURL = function (url) {
  69895. var a = document.createElement('a');
  69896. a.href = url;
  69897. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69898. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69899. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69900. return absLocation;
  69901. };
  69902. Database._ReturnFullUrlLocation = function (url) {
  69903. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69904. return (Database._ParseURL(window.location.href) + url);
  69905. }
  69906. else {
  69907. return url;
  69908. }
  69909. };
  69910. return Database;
  69911. }());
  69912. BABYLON.Database = Database;
  69913. })(BABYLON || (BABYLON = {}));
  69914. //# sourceMappingURL=babylon.database.js.map
  69915. var BABYLON;
  69916. (function (BABYLON) {
  69917. var FresnelParameters = /** @class */ (function () {
  69918. function FresnelParameters() {
  69919. this._isEnabled = true;
  69920. this.leftColor = BABYLON.Color3.White();
  69921. this.rightColor = BABYLON.Color3.Black();
  69922. this.bias = 0;
  69923. this.power = 1;
  69924. }
  69925. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69926. get: function () {
  69927. return this._isEnabled;
  69928. },
  69929. set: function (value) {
  69930. if (this._isEnabled === value) {
  69931. return;
  69932. }
  69933. this._isEnabled = value;
  69934. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69935. },
  69936. enumerable: true,
  69937. configurable: true
  69938. });
  69939. FresnelParameters.prototype.clone = function () {
  69940. var newFresnelParameters = new FresnelParameters();
  69941. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69942. return newFresnelParameters;
  69943. };
  69944. FresnelParameters.prototype.serialize = function () {
  69945. var serializationObject = {};
  69946. serializationObject.isEnabled = this.isEnabled;
  69947. serializationObject.leftColor = this.leftColor.asArray();
  69948. serializationObject.rightColor = this.rightColor.asArray();
  69949. serializationObject.bias = this.bias;
  69950. serializationObject.power = this.power;
  69951. return serializationObject;
  69952. };
  69953. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69954. var fresnelParameters = new FresnelParameters();
  69955. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69956. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69957. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69958. fresnelParameters.bias = parsedFresnelParameters.bias;
  69959. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69960. return fresnelParameters;
  69961. };
  69962. return FresnelParameters;
  69963. }());
  69964. BABYLON.FresnelParameters = FresnelParameters;
  69965. })(BABYLON || (BABYLON = {}));
  69966. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69967. var BABYLON;
  69968. (function (BABYLON) {
  69969. var MultiMaterial = /** @class */ (function (_super) {
  69970. __extends(MultiMaterial, _super);
  69971. function MultiMaterial(name, scene) {
  69972. var _this = _super.call(this, name, scene, true) || this;
  69973. scene.multiMaterials.push(_this);
  69974. _this.subMaterials = new Array();
  69975. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69976. return _this;
  69977. }
  69978. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69979. get: function () {
  69980. return this._subMaterials;
  69981. },
  69982. set: function (value) {
  69983. this._subMaterials = value;
  69984. this._hookArray(value);
  69985. },
  69986. enumerable: true,
  69987. configurable: true
  69988. });
  69989. MultiMaterial.prototype._hookArray = function (array) {
  69990. var _this = this;
  69991. var oldPush = array.push;
  69992. array.push = function () {
  69993. var items = [];
  69994. for (var _i = 0; _i < arguments.length; _i++) {
  69995. items[_i] = arguments[_i];
  69996. }
  69997. var result = oldPush.apply(array, items);
  69998. _this._markAllSubMeshesAsTexturesDirty();
  69999. return result;
  70000. };
  70001. var oldSplice = array.splice;
  70002. array.splice = function (index, deleteCount) {
  70003. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70004. _this._markAllSubMeshesAsTexturesDirty();
  70005. return deleted;
  70006. };
  70007. };
  70008. // Properties
  70009. MultiMaterial.prototype.getSubMaterial = function (index) {
  70010. if (index < 0 || index >= this.subMaterials.length) {
  70011. return this.getScene().defaultMaterial;
  70012. }
  70013. return this.subMaterials[index];
  70014. };
  70015. MultiMaterial.prototype.getActiveTextures = function () {
  70016. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70017. if (subMaterial) {
  70018. return subMaterial.getActiveTextures();
  70019. }
  70020. else {
  70021. return [];
  70022. }
  70023. }));
  70024. var _a;
  70025. };
  70026. // Methods
  70027. MultiMaterial.prototype.getClassName = function () {
  70028. return "MultiMaterial";
  70029. };
  70030. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70031. for (var index = 0; index < this.subMaterials.length; index++) {
  70032. var subMaterial = this.subMaterials[index];
  70033. if (subMaterial) {
  70034. if (subMaterial.storeEffectOnSubMeshes) {
  70035. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70036. return false;
  70037. }
  70038. continue;
  70039. }
  70040. if (!subMaterial.isReady(mesh)) {
  70041. return false;
  70042. }
  70043. }
  70044. }
  70045. return true;
  70046. };
  70047. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70048. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70049. for (var index = 0; index < this.subMaterials.length; index++) {
  70050. var subMaterial = null;
  70051. var current = this.subMaterials[index];
  70052. if (cloneChildren && current) {
  70053. subMaterial = current.clone(name + "-" + current.name);
  70054. }
  70055. else {
  70056. subMaterial = this.subMaterials[index];
  70057. }
  70058. newMultiMaterial.subMaterials.push(subMaterial);
  70059. }
  70060. return newMultiMaterial;
  70061. };
  70062. MultiMaterial.prototype.serialize = function () {
  70063. var serializationObject = {};
  70064. serializationObject.name = this.name;
  70065. serializationObject.id = this.id;
  70066. if (BABYLON.Tags) {
  70067. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70068. }
  70069. serializationObject.materials = [];
  70070. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70071. var subMat = this.subMaterials[matIndex];
  70072. if (subMat) {
  70073. serializationObject.materials.push(subMat.id);
  70074. }
  70075. else {
  70076. serializationObject.materials.push(null);
  70077. }
  70078. }
  70079. return serializationObject;
  70080. };
  70081. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70082. var scene = this.getScene();
  70083. if (!scene) {
  70084. return;
  70085. }
  70086. var index = scene.multiMaterials.indexOf(this);
  70087. if (index >= 0) {
  70088. scene.multiMaterials.splice(index, 1);
  70089. }
  70090. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70091. };
  70092. return MultiMaterial;
  70093. }(BABYLON.Material));
  70094. BABYLON.MultiMaterial = MultiMaterial;
  70095. })(BABYLON || (BABYLON = {}));
  70096. //# sourceMappingURL=babylon.multiMaterial.js.map
  70097. var BABYLON;
  70098. (function (BABYLON) {
  70099. var FreeCameraTouchInput = /** @class */ (function () {
  70100. function FreeCameraTouchInput() {
  70101. this._offsetX = null;
  70102. this._offsetY = null;
  70103. this._pointerPressed = new Array();
  70104. this.touchAngularSensibility = 200000.0;
  70105. this.touchMoveSensibility = 250.0;
  70106. }
  70107. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70108. var _this = this;
  70109. var previousPosition = null;
  70110. if (this._pointerInput === undefined) {
  70111. this._onLostFocus = function (evt) {
  70112. _this._offsetX = null;
  70113. _this._offsetY = null;
  70114. };
  70115. this._pointerInput = function (p, s) {
  70116. var evt = p.event;
  70117. if (evt.pointerType === "mouse") {
  70118. return;
  70119. }
  70120. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70121. if (!noPreventDefault) {
  70122. evt.preventDefault();
  70123. }
  70124. _this._pointerPressed.push(evt.pointerId);
  70125. if (_this._pointerPressed.length !== 1) {
  70126. return;
  70127. }
  70128. previousPosition = {
  70129. x: evt.clientX,
  70130. y: evt.clientY
  70131. };
  70132. }
  70133. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70134. if (!noPreventDefault) {
  70135. evt.preventDefault();
  70136. }
  70137. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70138. if (index === -1) {
  70139. return;
  70140. }
  70141. _this._pointerPressed.splice(index, 1);
  70142. if (index != 0) {
  70143. return;
  70144. }
  70145. previousPosition = null;
  70146. _this._offsetX = null;
  70147. _this._offsetY = null;
  70148. }
  70149. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70150. if (!noPreventDefault) {
  70151. evt.preventDefault();
  70152. }
  70153. if (!previousPosition) {
  70154. return;
  70155. }
  70156. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70157. if (index != 0) {
  70158. return;
  70159. }
  70160. _this._offsetX = evt.clientX - previousPosition.x;
  70161. _this._offsetY = -(evt.clientY - previousPosition.y);
  70162. }
  70163. };
  70164. }
  70165. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70166. if (this._onLostFocus) {
  70167. element.addEventListener("blur", this._onLostFocus);
  70168. }
  70169. };
  70170. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70171. if (this._pointerInput && element) {
  70172. if (this._observer) {
  70173. this.camera.getScene().onPointerObservable.remove(this._observer);
  70174. this._observer = null;
  70175. }
  70176. if (this._onLostFocus) {
  70177. element.removeEventListener("blur", this._onLostFocus);
  70178. this._onLostFocus = null;
  70179. }
  70180. this._pointerPressed = [];
  70181. this._offsetX = null;
  70182. this._offsetY = null;
  70183. }
  70184. };
  70185. FreeCameraTouchInput.prototype.checkInputs = function () {
  70186. if (this._offsetX && this._offsetY) {
  70187. var camera = this.camera;
  70188. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70189. if (this._pointerPressed.length > 1) {
  70190. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70191. }
  70192. else {
  70193. var speed = camera._computeLocalCameraSpeed();
  70194. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70195. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70196. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70197. }
  70198. }
  70199. };
  70200. FreeCameraTouchInput.prototype.getClassName = function () {
  70201. return "FreeCameraTouchInput";
  70202. };
  70203. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70204. return "touch";
  70205. };
  70206. __decorate([
  70207. BABYLON.serialize()
  70208. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70209. __decorate([
  70210. BABYLON.serialize()
  70211. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70212. return FreeCameraTouchInput;
  70213. }());
  70214. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70215. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70216. })(BABYLON || (BABYLON = {}));
  70217. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70218. var BABYLON;
  70219. (function (BABYLON) {
  70220. // We're mainly based on the logic defined into the FreeCamera code
  70221. var TouchCamera = /** @class */ (function (_super) {
  70222. __extends(TouchCamera, _super);
  70223. //-- end properties for backward compatibility for inputs
  70224. function TouchCamera(name, position, scene) {
  70225. var _this = _super.call(this, name, position, scene) || this;
  70226. _this.inputs.addTouch();
  70227. _this._setupInputs();
  70228. return _this;
  70229. }
  70230. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70231. //-- Begin properties for backward compatibility for inputs
  70232. get: function () {
  70233. var touch = this.inputs.attached["touch"];
  70234. if (touch)
  70235. return touch.touchAngularSensibility;
  70236. return 0;
  70237. },
  70238. set: function (value) {
  70239. var touch = this.inputs.attached["touch"];
  70240. if (touch)
  70241. touch.touchAngularSensibility = value;
  70242. },
  70243. enumerable: true,
  70244. configurable: true
  70245. });
  70246. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70247. get: function () {
  70248. var touch = this.inputs.attached["touch"];
  70249. if (touch)
  70250. return touch.touchMoveSensibility;
  70251. return 0;
  70252. },
  70253. set: function (value) {
  70254. var touch = this.inputs.attached["touch"];
  70255. if (touch)
  70256. touch.touchMoveSensibility = value;
  70257. },
  70258. enumerable: true,
  70259. configurable: true
  70260. });
  70261. TouchCamera.prototype.getClassName = function () {
  70262. return "TouchCamera";
  70263. };
  70264. TouchCamera.prototype._setupInputs = function () {
  70265. var mouse = this.inputs.attached["mouse"];
  70266. if (mouse) {
  70267. mouse.touchEnabled = false;
  70268. }
  70269. };
  70270. return TouchCamera;
  70271. }(BABYLON.FreeCamera));
  70272. BABYLON.TouchCamera = TouchCamera;
  70273. })(BABYLON || (BABYLON = {}));
  70274. //# sourceMappingURL=babylon.touchCamera.js.map
  70275. var BABYLON;
  70276. (function (BABYLON) {
  70277. var ProceduralTexture = /** @class */ (function (_super) {
  70278. __extends(ProceduralTexture, _super);
  70279. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70280. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70281. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70282. if (isCube === void 0) { isCube = false; }
  70283. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70284. _this.isCube = isCube;
  70285. _this.isEnabled = true;
  70286. _this._currentRefreshId = -1;
  70287. _this._refreshRate = 1;
  70288. _this._vertexBuffers = {};
  70289. _this._uniforms = new Array();
  70290. _this._samplers = new Array();
  70291. _this._textures = {};
  70292. _this._floats = {};
  70293. _this._floatsArrays = {};
  70294. _this._colors3 = {};
  70295. _this._colors4 = {};
  70296. _this._vectors2 = {};
  70297. _this._vectors3 = {};
  70298. _this._matrices = {};
  70299. _this._fallbackTextureUsed = false;
  70300. scene.proceduralTextures.push(_this);
  70301. _this._engine = scene.getEngine();
  70302. _this.name = name;
  70303. _this.isRenderTarget = true;
  70304. _this._size = size;
  70305. _this._generateMipMaps = generateMipMaps;
  70306. _this.setFragment(fragment);
  70307. _this._fallbackTexture = fallbackTexture;
  70308. if (isCube) {
  70309. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70310. _this.setFloat("face", 0);
  70311. }
  70312. else {
  70313. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70314. }
  70315. // VBO
  70316. var vertices = [];
  70317. vertices.push(1, 1);
  70318. vertices.push(-1, 1);
  70319. vertices.push(-1, -1);
  70320. vertices.push(1, -1);
  70321. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70322. _this._createIndexBuffer();
  70323. return _this;
  70324. }
  70325. ProceduralTexture.prototype._createIndexBuffer = function () {
  70326. var engine = this._engine;
  70327. // Indices
  70328. var indices = [];
  70329. indices.push(0);
  70330. indices.push(1);
  70331. indices.push(2);
  70332. indices.push(0);
  70333. indices.push(2);
  70334. indices.push(3);
  70335. this._indexBuffer = engine.createIndexBuffer(indices);
  70336. };
  70337. ProceduralTexture.prototype._rebuild = function () {
  70338. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70339. if (vb) {
  70340. vb._rebuild();
  70341. }
  70342. this._createIndexBuffer();
  70343. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70344. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70345. }
  70346. };
  70347. ProceduralTexture.prototype.reset = function () {
  70348. if (this._effect === undefined) {
  70349. return;
  70350. }
  70351. var engine = this._engine;
  70352. engine._releaseEffect(this._effect);
  70353. };
  70354. ProceduralTexture.prototype.isReady = function () {
  70355. var _this = this;
  70356. var engine = this._engine;
  70357. var shaders;
  70358. if (!this._fragment) {
  70359. return false;
  70360. }
  70361. if (this._fallbackTextureUsed) {
  70362. return true;
  70363. }
  70364. if (this._fragment.fragmentElement !== undefined) {
  70365. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70366. }
  70367. else {
  70368. shaders = { vertex: "procedural", fragment: this._fragment };
  70369. }
  70370. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70371. _this.releaseInternalTexture();
  70372. if (_this._fallbackTexture) {
  70373. _this._texture = _this._fallbackTexture._texture;
  70374. if (_this._texture) {
  70375. _this._texture.incrementReferences();
  70376. }
  70377. }
  70378. _this._fallbackTextureUsed = true;
  70379. });
  70380. return this._effect.isReady();
  70381. };
  70382. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70383. this._currentRefreshId = -1;
  70384. };
  70385. ProceduralTexture.prototype.setFragment = function (fragment) {
  70386. this._fragment = fragment;
  70387. };
  70388. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70389. get: function () {
  70390. return this._refreshRate;
  70391. },
  70392. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70393. set: function (value) {
  70394. this._refreshRate = value;
  70395. this.resetRefreshCounter();
  70396. },
  70397. enumerable: true,
  70398. configurable: true
  70399. });
  70400. ProceduralTexture.prototype._shouldRender = function () {
  70401. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70402. return false;
  70403. }
  70404. if (this._fallbackTextureUsed) {
  70405. return false;
  70406. }
  70407. if (this._currentRefreshId === -1) { // At least render once
  70408. this._currentRefreshId = 1;
  70409. return true;
  70410. }
  70411. if (this.refreshRate === this._currentRefreshId) {
  70412. this._currentRefreshId = 1;
  70413. return true;
  70414. }
  70415. this._currentRefreshId++;
  70416. return false;
  70417. };
  70418. ProceduralTexture.prototype.getRenderSize = function () {
  70419. return this._size;
  70420. };
  70421. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70422. if (this._fallbackTextureUsed) {
  70423. return;
  70424. }
  70425. this.releaseInternalTexture();
  70426. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70427. // Update properties
  70428. this._size = size;
  70429. this._generateMipMaps = generateMipMaps;
  70430. };
  70431. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70432. if (this._uniforms.indexOf(uniformName) === -1) {
  70433. this._uniforms.push(uniformName);
  70434. }
  70435. };
  70436. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70437. if (this._samplers.indexOf(name) === -1) {
  70438. this._samplers.push(name);
  70439. }
  70440. this._textures[name] = texture;
  70441. return this;
  70442. };
  70443. ProceduralTexture.prototype.setFloat = function (name, value) {
  70444. this._checkUniform(name);
  70445. this._floats[name] = value;
  70446. return this;
  70447. };
  70448. ProceduralTexture.prototype.setFloats = function (name, value) {
  70449. this._checkUniform(name);
  70450. this._floatsArrays[name] = value;
  70451. return this;
  70452. };
  70453. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70454. this._checkUniform(name);
  70455. this._colors3[name] = value;
  70456. return this;
  70457. };
  70458. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70459. this._checkUniform(name);
  70460. this._colors4[name] = value;
  70461. return this;
  70462. };
  70463. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70464. this._checkUniform(name);
  70465. this._vectors2[name] = value;
  70466. return this;
  70467. };
  70468. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70469. this._checkUniform(name);
  70470. this._vectors3[name] = value;
  70471. return this;
  70472. };
  70473. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70474. this._checkUniform(name);
  70475. this._matrices[name] = value;
  70476. return this;
  70477. };
  70478. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70479. var scene = this.getScene();
  70480. if (!scene) {
  70481. return;
  70482. }
  70483. var engine = this._engine;
  70484. // Render
  70485. engine.enableEffect(this._effect);
  70486. engine.setState(false);
  70487. // Texture
  70488. for (var name in this._textures) {
  70489. this._effect.setTexture(name, this._textures[name]);
  70490. }
  70491. // Float
  70492. for (name in this._floats) {
  70493. this._effect.setFloat(name, this._floats[name]);
  70494. }
  70495. // Floats
  70496. for (name in this._floatsArrays) {
  70497. this._effect.setArray(name, this._floatsArrays[name]);
  70498. }
  70499. // Color3
  70500. for (name in this._colors3) {
  70501. this._effect.setColor3(name, this._colors3[name]);
  70502. }
  70503. // Color4
  70504. for (name in this._colors4) {
  70505. var color = this._colors4[name];
  70506. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70507. }
  70508. // Vector2
  70509. for (name in this._vectors2) {
  70510. this._effect.setVector2(name, this._vectors2[name]);
  70511. }
  70512. // Vector3
  70513. for (name in this._vectors3) {
  70514. this._effect.setVector3(name, this._vectors3[name]);
  70515. }
  70516. // Matrix
  70517. for (name in this._matrices) {
  70518. this._effect.setMatrix(name, this._matrices[name]);
  70519. }
  70520. if (!this._texture) {
  70521. return;
  70522. }
  70523. if (this.isCube) {
  70524. for (var face = 0; face < 6; face++) {
  70525. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70526. // VBOs
  70527. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70528. this._effect.setFloat("face", face);
  70529. // Clear
  70530. engine.clear(scene.clearColor, true, true, true);
  70531. // Draw order
  70532. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70533. // Mipmaps
  70534. if (face === 5) {
  70535. engine.generateMipMapsForCubemap(this._texture);
  70536. }
  70537. }
  70538. }
  70539. else {
  70540. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70541. // VBOs
  70542. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70543. // Clear
  70544. engine.clear(scene.clearColor, true, true, true);
  70545. // Draw order
  70546. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70547. }
  70548. // Unbind
  70549. engine.unBindFramebuffer(this._texture, this.isCube);
  70550. if (this.onGenerated) {
  70551. this.onGenerated();
  70552. }
  70553. };
  70554. ProceduralTexture.prototype.clone = function () {
  70555. var textureSize = this.getSize();
  70556. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70557. // Base texture
  70558. newTexture.hasAlpha = this.hasAlpha;
  70559. newTexture.level = this.level;
  70560. // RenderTarget Texture
  70561. newTexture.coordinatesMode = this.coordinatesMode;
  70562. return newTexture;
  70563. };
  70564. ProceduralTexture.prototype.dispose = function () {
  70565. var scene = this.getScene();
  70566. if (!scene) {
  70567. return;
  70568. }
  70569. var index = scene.proceduralTextures.indexOf(this);
  70570. if (index >= 0) {
  70571. scene.proceduralTextures.splice(index, 1);
  70572. }
  70573. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70574. if (vertexBuffer) {
  70575. vertexBuffer.dispose();
  70576. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70577. }
  70578. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70579. this._indexBuffer = null;
  70580. }
  70581. _super.prototype.dispose.call(this);
  70582. };
  70583. __decorate([
  70584. BABYLON.serialize()
  70585. ], ProceduralTexture.prototype, "_size", void 0);
  70586. __decorate([
  70587. BABYLON.serialize()
  70588. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70589. __decorate([
  70590. BABYLON.serialize()
  70591. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70592. __decorate([
  70593. BABYLON.serialize()
  70594. ], ProceduralTexture.prototype, "refreshRate", null);
  70595. return ProceduralTexture;
  70596. }(BABYLON.Texture));
  70597. BABYLON.ProceduralTexture = ProceduralTexture;
  70598. })(BABYLON || (BABYLON = {}));
  70599. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70600. var BABYLON;
  70601. (function (BABYLON) {
  70602. var CustomProceduralTexture = /** @class */ (function (_super) {
  70603. __extends(CustomProceduralTexture, _super);
  70604. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70605. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70606. _this._animate = true;
  70607. _this._time = 0;
  70608. _this._texturePath = texturePath;
  70609. //Try to load json
  70610. _this.loadJson(texturePath);
  70611. _this.refreshRate = 1;
  70612. return _this;
  70613. }
  70614. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70615. var _this = this;
  70616. var noConfigFile = function () {
  70617. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70618. try {
  70619. _this.setFragment(_this._texturePath);
  70620. }
  70621. catch (ex) {
  70622. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70623. }
  70624. };
  70625. var configFileUrl = jsonUrl + "/config.json";
  70626. var xhr = new XMLHttpRequest();
  70627. xhr.open("GET", configFileUrl, true);
  70628. xhr.addEventListener("load", function () {
  70629. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70630. try {
  70631. _this._config = JSON.parse(xhr.response);
  70632. _this.updateShaderUniforms();
  70633. _this.updateTextures();
  70634. _this.setFragment(_this._texturePath + "/custom");
  70635. _this._animate = _this._config.animate;
  70636. _this.refreshRate = _this._config.refreshrate;
  70637. }
  70638. catch (ex) {
  70639. noConfigFile();
  70640. }
  70641. }
  70642. else {
  70643. noConfigFile();
  70644. }
  70645. }, false);
  70646. xhr.addEventListener("error", function () {
  70647. noConfigFile();
  70648. }, false);
  70649. try {
  70650. xhr.send();
  70651. }
  70652. catch (ex) {
  70653. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70654. }
  70655. };
  70656. CustomProceduralTexture.prototype.isReady = function () {
  70657. if (!_super.prototype.isReady.call(this)) {
  70658. return false;
  70659. }
  70660. for (var name in this._textures) {
  70661. var texture = this._textures[name];
  70662. if (!texture.isReady()) {
  70663. return false;
  70664. }
  70665. }
  70666. return true;
  70667. };
  70668. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70669. var scene = this.getScene();
  70670. if (this._animate && scene) {
  70671. this._time += scene.getAnimationRatio() * 0.03;
  70672. this.updateShaderUniforms();
  70673. }
  70674. _super.prototype.render.call(this, useCameraPostProcess);
  70675. };
  70676. CustomProceduralTexture.prototype.updateTextures = function () {
  70677. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70678. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70679. }
  70680. };
  70681. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70682. if (this._config) {
  70683. for (var j = 0; j < this._config.uniforms.length; j++) {
  70684. var uniform = this._config.uniforms[j];
  70685. switch (uniform.type) {
  70686. case "float":
  70687. this.setFloat(uniform.name, uniform.value);
  70688. break;
  70689. case "color3":
  70690. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70691. break;
  70692. case "color4":
  70693. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70694. break;
  70695. case "vector2":
  70696. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70697. break;
  70698. case "vector3":
  70699. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70700. break;
  70701. }
  70702. }
  70703. }
  70704. this.setFloat("time", this._time);
  70705. };
  70706. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70707. get: function () {
  70708. return this._animate;
  70709. },
  70710. set: function (value) {
  70711. this._animate = value;
  70712. },
  70713. enumerable: true,
  70714. configurable: true
  70715. });
  70716. return CustomProceduralTexture;
  70717. }(BABYLON.ProceduralTexture));
  70718. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70719. })(BABYLON || (BABYLON = {}));
  70720. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70721. var BABYLON;
  70722. (function (BABYLON) {
  70723. var FreeCameraGamepadInput = /** @class */ (function () {
  70724. function FreeCameraGamepadInput() {
  70725. this.gamepadAngularSensibility = 200;
  70726. this.gamepadMoveSensibility = 40;
  70727. // private members
  70728. this._cameraTransform = BABYLON.Matrix.Identity();
  70729. this._deltaTransform = BABYLON.Vector3.Zero();
  70730. this._vector3 = BABYLON.Vector3.Zero();
  70731. this._vector2 = BABYLON.Vector2.Zero();
  70732. }
  70733. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70734. var _this = this;
  70735. var manager = this.camera.getScene().gamepadManager;
  70736. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70737. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70738. // prioritize XBOX gamepads.
  70739. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70740. _this.gamepad = gamepad;
  70741. }
  70742. }
  70743. });
  70744. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70745. if (_this.gamepad === gamepad) {
  70746. _this.gamepad = null;
  70747. }
  70748. });
  70749. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70750. };
  70751. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70752. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70753. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70754. this.gamepad = null;
  70755. };
  70756. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70757. if (this.gamepad && this.gamepad.leftStick) {
  70758. var camera = this.camera;
  70759. var LSValues = this.gamepad.leftStick;
  70760. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70761. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70762. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70763. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70764. var RSValues = this.gamepad.rightStick;
  70765. if (RSValues) {
  70766. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70767. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70768. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70769. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70770. }
  70771. else {
  70772. RSValues = { x: 0, y: 0 };
  70773. }
  70774. if (!camera.rotationQuaternion) {
  70775. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70776. }
  70777. else {
  70778. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70779. }
  70780. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70781. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70782. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70783. camera.cameraDirection.addInPlace(this._deltaTransform);
  70784. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70785. camera.cameraRotation.addInPlace(this._vector2);
  70786. }
  70787. };
  70788. FreeCameraGamepadInput.prototype.getClassName = function () {
  70789. return "FreeCameraGamepadInput";
  70790. };
  70791. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70792. return "gamepad";
  70793. };
  70794. __decorate([
  70795. BABYLON.serialize()
  70796. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70797. __decorate([
  70798. BABYLON.serialize()
  70799. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70800. return FreeCameraGamepadInput;
  70801. }());
  70802. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70803. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70804. })(BABYLON || (BABYLON = {}));
  70805. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70806. var BABYLON;
  70807. (function (BABYLON) {
  70808. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70809. function ArcRotateCameraGamepadInput() {
  70810. this.gamepadRotationSensibility = 80;
  70811. this.gamepadMoveSensibility = 40;
  70812. }
  70813. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70814. var _this = this;
  70815. var manager = this.camera.getScene().gamepadManager;
  70816. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70817. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70818. // prioritize XBOX gamepads.
  70819. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70820. _this.gamepad = gamepad;
  70821. }
  70822. }
  70823. });
  70824. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70825. if (_this.gamepad === gamepad) {
  70826. _this.gamepad = null;
  70827. }
  70828. });
  70829. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70830. };
  70831. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70832. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70833. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70834. this.gamepad = null;
  70835. };
  70836. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70837. if (this.gamepad) {
  70838. var camera = this.camera;
  70839. var RSValues = this.gamepad.rightStick;
  70840. if (RSValues) {
  70841. if (RSValues.x != 0) {
  70842. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70843. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70844. camera.inertialAlphaOffset += normalizedRX;
  70845. }
  70846. }
  70847. if (RSValues.y != 0) {
  70848. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70849. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70850. camera.inertialBetaOffset += normalizedRY;
  70851. }
  70852. }
  70853. }
  70854. var LSValues = this.gamepad.leftStick;
  70855. if (LSValues && LSValues.y != 0) {
  70856. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70857. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70858. this.camera.inertialRadiusOffset -= normalizedLY;
  70859. }
  70860. }
  70861. }
  70862. };
  70863. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70864. return "ArcRotateCameraGamepadInput";
  70865. };
  70866. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70867. return "gamepad";
  70868. };
  70869. __decorate([
  70870. BABYLON.serialize()
  70871. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70872. __decorate([
  70873. BABYLON.serialize()
  70874. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70875. return ArcRotateCameraGamepadInput;
  70876. }());
  70877. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70878. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70879. })(BABYLON || (BABYLON = {}));
  70880. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70881. var BABYLON;
  70882. (function (BABYLON) {
  70883. var GamepadManager = /** @class */ (function () {
  70884. function GamepadManager(_scene) {
  70885. var _this = this;
  70886. this._scene = _scene;
  70887. this._babylonGamepads = [];
  70888. this._oneGamepadConnected = false;
  70889. this._isMonitoring = false;
  70890. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70891. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70892. this._gamepadEventSupported = false;
  70893. }
  70894. else {
  70895. this._gamepadEventSupported = 'GamepadEvent' in window;
  70896. this._gamepadSupport = (navigator.getGamepads ||
  70897. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70898. }
  70899. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70900. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70901. for (var i in _this._babylonGamepads) {
  70902. var gamepad = _this._babylonGamepads[i];
  70903. if (gamepad && gamepad._isConnected) {
  70904. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70905. }
  70906. }
  70907. });
  70908. this._onGamepadConnectedEvent = function (evt) {
  70909. var gamepad = evt.gamepad;
  70910. if (gamepad.index in _this._babylonGamepads) {
  70911. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70912. return;
  70913. }
  70914. }
  70915. var newGamepad;
  70916. if (_this._babylonGamepads[gamepad.index]) {
  70917. newGamepad = _this._babylonGamepads[gamepad.index];
  70918. newGamepad.browserGamepad = gamepad;
  70919. newGamepad._isConnected = true;
  70920. }
  70921. else {
  70922. newGamepad = _this._addNewGamepad(gamepad);
  70923. }
  70924. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70925. _this._startMonitoringGamepads();
  70926. };
  70927. this._onGamepadDisconnectedEvent = function (evt) {
  70928. var gamepad = evt.gamepad;
  70929. // Remove the gamepad from the list of gamepads to monitor.
  70930. for (var i in _this._babylonGamepads) {
  70931. if (_this._babylonGamepads[i].index === gamepad.index) {
  70932. var disconnectedGamepad = _this._babylonGamepads[i];
  70933. disconnectedGamepad._isConnected = false;
  70934. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70935. break;
  70936. }
  70937. }
  70938. };
  70939. if (this._gamepadSupport) {
  70940. //first add already-connected gamepads
  70941. this._updateGamepadObjects();
  70942. if (this._babylonGamepads.length) {
  70943. this._startMonitoringGamepads();
  70944. }
  70945. // Checking if the gamepad connected event is supported (like in Firefox)
  70946. if (this._gamepadEventSupported) {
  70947. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70948. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70949. }
  70950. else {
  70951. this._startMonitoringGamepads();
  70952. }
  70953. }
  70954. }
  70955. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70956. get: function () {
  70957. return this._babylonGamepads;
  70958. },
  70959. enumerable: true,
  70960. configurable: true
  70961. });
  70962. GamepadManager.prototype.getGamepadByType = function (type) {
  70963. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70964. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70965. var gamepad = _a[_i];
  70966. if (gamepad && gamepad.type === type) {
  70967. return gamepad;
  70968. }
  70969. }
  70970. return null;
  70971. };
  70972. GamepadManager.prototype.dispose = function () {
  70973. if (this._gamepadEventSupported) {
  70974. if (this._onGamepadConnectedEvent) {
  70975. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70976. }
  70977. if (this._onGamepadDisconnectedEvent) {
  70978. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70979. }
  70980. this._onGamepadConnectedEvent = null;
  70981. this._onGamepadDisconnectedEvent = null;
  70982. }
  70983. this._babylonGamepads.forEach(function (gamepad) {
  70984. gamepad.dispose();
  70985. });
  70986. this.onGamepadConnectedObservable.clear();
  70987. this.onGamepadDisconnectedObservable.clear();
  70988. this._oneGamepadConnected = false;
  70989. this._stopMonitoringGamepads();
  70990. this._babylonGamepads = [];
  70991. };
  70992. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70993. if (!this._oneGamepadConnected) {
  70994. this._oneGamepadConnected = true;
  70995. }
  70996. var newGamepad;
  70997. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70998. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70999. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71000. }
  71001. // if pose is supported, use the (WebVR) pose enabled controller
  71002. else if (gamepad.pose) {
  71003. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71004. }
  71005. else {
  71006. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71007. }
  71008. this._babylonGamepads[newGamepad.index] = newGamepad;
  71009. return newGamepad;
  71010. };
  71011. GamepadManager.prototype._startMonitoringGamepads = function () {
  71012. if (!this._isMonitoring) {
  71013. this._isMonitoring = true;
  71014. //back-comp
  71015. if (!this._scene) {
  71016. this._checkGamepadsStatus();
  71017. }
  71018. }
  71019. };
  71020. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71021. this._isMonitoring = false;
  71022. };
  71023. GamepadManager.prototype._checkGamepadsStatus = function () {
  71024. var _this = this;
  71025. // Hack to be compatible Chrome
  71026. this._updateGamepadObjects();
  71027. for (var i in this._babylonGamepads) {
  71028. var gamepad = this._babylonGamepads[i];
  71029. if (!gamepad || !gamepad.isConnected) {
  71030. continue;
  71031. }
  71032. gamepad.update();
  71033. }
  71034. if (this._isMonitoring && !this._scene) {
  71035. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71036. }
  71037. };
  71038. // This function is called only on Chrome, which does not properly support
  71039. // connection/disconnection events and forces you to recopy again the gamepad object
  71040. GamepadManager.prototype._updateGamepadObjects = function () {
  71041. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71042. for (var i = 0; i < gamepads.length; i++) {
  71043. var gamepad = gamepads[i];
  71044. if (gamepad) {
  71045. if (!this._babylonGamepads[gamepad.index]) {
  71046. var newGamepad = this._addNewGamepad(gamepad);
  71047. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71048. }
  71049. else {
  71050. // Forced to copy again this object for Chrome for unknown reason
  71051. this._babylonGamepads[i].browserGamepad = gamepad;
  71052. if (!this._babylonGamepads[i].isConnected) {
  71053. this._babylonGamepads[i]._isConnected = true;
  71054. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71055. }
  71056. }
  71057. }
  71058. }
  71059. };
  71060. return GamepadManager;
  71061. }());
  71062. BABYLON.GamepadManager = GamepadManager;
  71063. })(BABYLON || (BABYLON = {}));
  71064. //# sourceMappingURL=babylon.gamepadManager.js.map
  71065. var BABYLON;
  71066. (function (BABYLON) {
  71067. var StickValues = /** @class */ (function () {
  71068. function StickValues(x, y) {
  71069. this.x = x;
  71070. this.y = y;
  71071. }
  71072. return StickValues;
  71073. }());
  71074. BABYLON.StickValues = StickValues;
  71075. var Gamepad = /** @class */ (function () {
  71076. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71077. if (leftStickX === void 0) { leftStickX = 0; }
  71078. if (leftStickY === void 0) { leftStickY = 1; }
  71079. if (rightStickX === void 0) { rightStickX = 2; }
  71080. if (rightStickY === void 0) { rightStickY = 3; }
  71081. this.id = id;
  71082. this.index = index;
  71083. this.browserGamepad = browserGamepad;
  71084. this._isConnected = true;
  71085. this._invertLeftStickY = false;
  71086. this.type = Gamepad.GAMEPAD;
  71087. this._leftStickAxisX = leftStickX;
  71088. this._leftStickAxisY = leftStickY;
  71089. this._rightStickAxisX = rightStickX;
  71090. this._rightStickAxisY = rightStickY;
  71091. if (this.browserGamepad.axes.length >= 2) {
  71092. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71093. }
  71094. if (this.browserGamepad.axes.length >= 4) {
  71095. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71096. }
  71097. }
  71098. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71099. get: function () {
  71100. return this._isConnected;
  71101. },
  71102. enumerable: true,
  71103. configurable: true
  71104. });
  71105. Gamepad.prototype.onleftstickchanged = function (callback) {
  71106. this._onleftstickchanged = callback;
  71107. };
  71108. Gamepad.prototype.onrightstickchanged = function (callback) {
  71109. this._onrightstickchanged = callback;
  71110. };
  71111. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71112. get: function () {
  71113. return this._leftStick;
  71114. },
  71115. set: function (newValues) {
  71116. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71117. this._onleftstickchanged(newValues);
  71118. }
  71119. this._leftStick = newValues;
  71120. },
  71121. enumerable: true,
  71122. configurable: true
  71123. });
  71124. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71125. get: function () {
  71126. return this._rightStick;
  71127. },
  71128. set: function (newValues) {
  71129. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71130. this._onrightstickchanged(newValues);
  71131. }
  71132. this._rightStick = newValues;
  71133. },
  71134. enumerable: true,
  71135. configurable: true
  71136. });
  71137. Gamepad.prototype.update = function () {
  71138. if (this._leftStick) {
  71139. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71140. if (this._invertLeftStickY) {
  71141. this.leftStick.y *= -1;
  71142. }
  71143. }
  71144. if (this._rightStick) {
  71145. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71146. }
  71147. };
  71148. Gamepad.prototype.dispose = function () {
  71149. };
  71150. Gamepad.GAMEPAD = 0;
  71151. Gamepad.GENERIC = 1;
  71152. Gamepad.XBOX = 2;
  71153. Gamepad.POSE_ENABLED = 3;
  71154. return Gamepad;
  71155. }());
  71156. BABYLON.Gamepad = Gamepad;
  71157. var GenericPad = /** @class */ (function (_super) {
  71158. __extends(GenericPad, _super);
  71159. function GenericPad(id, index, browserGamepad) {
  71160. var _this = _super.call(this, id, index, browserGamepad) || this;
  71161. _this.onButtonDownObservable = new BABYLON.Observable();
  71162. _this.onButtonUpObservable = new BABYLON.Observable();
  71163. _this.type = Gamepad.GENERIC;
  71164. _this._buttons = new Array(browserGamepad.buttons.length);
  71165. return _this;
  71166. }
  71167. GenericPad.prototype.onbuttondown = function (callback) {
  71168. this._onbuttondown = callback;
  71169. };
  71170. GenericPad.prototype.onbuttonup = function (callback) {
  71171. this._onbuttonup = callback;
  71172. };
  71173. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71174. if (newValue !== currentValue) {
  71175. if (newValue === 1) {
  71176. if (this._onbuttondown) {
  71177. this._onbuttondown(buttonIndex);
  71178. }
  71179. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71180. }
  71181. if (newValue === 0) {
  71182. if (this._onbuttonup) {
  71183. this._onbuttonup(buttonIndex);
  71184. }
  71185. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71186. }
  71187. }
  71188. return newValue;
  71189. };
  71190. GenericPad.prototype.update = function () {
  71191. _super.prototype.update.call(this);
  71192. for (var index = 0; index < this._buttons.length; index++) {
  71193. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71194. }
  71195. };
  71196. GenericPad.prototype.dispose = function () {
  71197. _super.prototype.dispose.call(this);
  71198. this.onButtonDownObservable.clear();
  71199. this.onButtonUpObservable.clear();
  71200. };
  71201. return GenericPad;
  71202. }(Gamepad));
  71203. BABYLON.GenericPad = GenericPad;
  71204. })(BABYLON || (BABYLON = {}));
  71205. //# sourceMappingURL=babylon.gamepad.js.map
  71206. var BABYLON;
  71207. (function (BABYLON) {
  71208. /**
  71209. * Defines supported buttons for XBox360 compatible gamepads
  71210. */
  71211. var Xbox360Button;
  71212. (function (Xbox360Button) {
  71213. /** A */
  71214. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71215. /** B */
  71216. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71217. /** X */
  71218. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71219. /** Y */
  71220. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71221. /** Start */
  71222. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71223. /** Back */
  71224. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71225. /** Left button */
  71226. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71227. /** Right button */
  71228. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71229. /** Left stick */
  71230. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71231. /** Right stick */
  71232. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71233. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71234. /** Defines values for XBox360 DPad */
  71235. var Xbox360Dpad;
  71236. (function (Xbox360Dpad) {
  71237. /** Up */
  71238. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71239. /** Down */
  71240. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71241. /** Left */
  71242. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71243. /** Right */
  71244. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71245. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71246. /**
  71247. * Defines a XBox360 gamepad
  71248. */
  71249. var Xbox360Pad = /** @class */ (function (_super) {
  71250. __extends(Xbox360Pad, _super);
  71251. /**
  71252. * Creates a new XBox360 gamepad object
  71253. * @param id defines the id of this gamepad
  71254. * @param index defines its index
  71255. * @param gamepad defines the internal HTML gamepad object
  71256. * @param xboxOne defines if it is a XBox One gamepad
  71257. */
  71258. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71259. if (xboxOne === void 0) { xboxOne = false; }
  71260. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71261. _this._leftTrigger = 0;
  71262. _this._rightTrigger = 0;
  71263. /** Observable raised when a button is pressed */
  71264. _this.onButtonDownObservable = new BABYLON.Observable();
  71265. /** Observable raised when a button is released */
  71266. _this.onButtonUpObservable = new BABYLON.Observable();
  71267. /** Observable raised when a pad is pressed */
  71268. _this.onPadDownObservable = new BABYLON.Observable();
  71269. /** Observable raised when a pad is released */
  71270. _this.onPadUpObservable = new BABYLON.Observable();
  71271. _this._buttonA = 0;
  71272. _this._buttonB = 0;
  71273. _this._buttonX = 0;
  71274. _this._buttonY = 0;
  71275. _this._buttonBack = 0;
  71276. _this._buttonStart = 0;
  71277. _this._buttonLB = 0;
  71278. _this._buttonRB = 0;
  71279. _this._buttonLeftStick = 0;
  71280. _this._buttonRightStick = 0;
  71281. _this._dPadUp = 0;
  71282. _this._dPadDown = 0;
  71283. _this._dPadLeft = 0;
  71284. _this._dPadRight = 0;
  71285. _this._isXboxOnePad = false;
  71286. _this.type = BABYLON.Gamepad.XBOX;
  71287. _this._isXboxOnePad = xboxOne;
  71288. return _this;
  71289. }
  71290. /**
  71291. * Defines the callback to call when left trigger is pressed
  71292. * @param callback defines the callback to use
  71293. */
  71294. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71295. this._onlefttriggerchanged = callback;
  71296. };
  71297. /**
  71298. * Defines the callback to call when right trigger is pressed
  71299. * @param callback defines the callback to use
  71300. */
  71301. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71302. this._onrighttriggerchanged = callback;
  71303. };
  71304. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71305. /**
  71306. * Gets or sets left trigger value
  71307. */
  71308. get: function () {
  71309. return this._leftTrigger;
  71310. },
  71311. set: function (newValue) {
  71312. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71313. this._onlefttriggerchanged(newValue);
  71314. }
  71315. this._leftTrigger = newValue;
  71316. },
  71317. enumerable: true,
  71318. configurable: true
  71319. });
  71320. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71321. /**
  71322. * Gets or sets right trigger value
  71323. */
  71324. get: function () {
  71325. return this._rightTrigger;
  71326. },
  71327. set: function (newValue) {
  71328. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71329. this._onrighttriggerchanged(newValue);
  71330. }
  71331. this._rightTrigger = newValue;
  71332. },
  71333. enumerable: true,
  71334. configurable: true
  71335. });
  71336. /**
  71337. * Defines the callback to call when a button is pressed
  71338. * @param callback defines the callback to use
  71339. */
  71340. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71341. this._onbuttondown = callback;
  71342. };
  71343. /**
  71344. * Defines the callback to call when a button is released
  71345. * @param callback defines the callback to use
  71346. */
  71347. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71348. this._onbuttonup = callback;
  71349. };
  71350. /**
  71351. * Defines the callback to call when a pad is pressed
  71352. * @param callback defines the callback to use
  71353. */
  71354. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71355. this._ondpaddown = callback;
  71356. };
  71357. /**
  71358. * Defines the callback to call when a pad is released
  71359. * @param callback defines the callback to use
  71360. */
  71361. Xbox360Pad.prototype.ondpadup = function (callback) {
  71362. this._ondpadup = callback;
  71363. };
  71364. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71365. if (newValue !== currentValue) {
  71366. if (newValue === 1) {
  71367. if (this._onbuttondown) {
  71368. this._onbuttondown(buttonType);
  71369. }
  71370. this.onButtonDownObservable.notifyObservers(buttonType);
  71371. }
  71372. if (newValue === 0) {
  71373. if (this._onbuttonup) {
  71374. this._onbuttonup(buttonType);
  71375. }
  71376. this.onButtonUpObservable.notifyObservers(buttonType);
  71377. }
  71378. }
  71379. return newValue;
  71380. };
  71381. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71382. if (newValue !== currentValue) {
  71383. if (newValue === 1) {
  71384. if (this._ondpaddown) {
  71385. this._ondpaddown(buttonType);
  71386. }
  71387. this.onPadDownObservable.notifyObservers(buttonType);
  71388. }
  71389. if (newValue === 0) {
  71390. if (this._ondpadup) {
  71391. this._ondpadup(buttonType);
  71392. }
  71393. this.onPadUpObservable.notifyObservers(buttonType);
  71394. }
  71395. }
  71396. return newValue;
  71397. };
  71398. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71399. /** Gets or sets value of A button */
  71400. get: function () {
  71401. return this._buttonA;
  71402. },
  71403. set: function (value) {
  71404. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71405. },
  71406. enumerable: true,
  71407. configurable: true
  71408. });
  71409. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71410. /** Gets or sets value of B button */
  71411. get: function () {
  71412. return this._buttonB;
  71413. },
  71414. set: function (value) {
  71415. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71416. },
  71417. enumerable: true,
  71418. configurable: true
  71419. });
  71420. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71421. /** Gets or sets value of X button */
  71422. get: function () {
  71423. return this._buttonX;
  71424. },
  71425. set: function (value) {
  71426. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71427. },
  71428. enumerable: true,
  71429. configurable: true
  71430. });
  71431. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71432. /** Gets or sets value of Y button */
  71433. get: function () {
  71434. return this._buttonY;
  71435. },
  71436. set: function (value) {
  71437. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71438. },
  71439. enumerable: true,
  71440. configurable: true
  71441. });
  71442. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71443. /** Gets or sets value of Start button */
  71444. get: function () {
  71445. return this._buttonStart;
  71446. },
  71447. set: function (value) {
  71448. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71449. },
  71450. enumerable: true,
  71451. configurable: true
  71452. });
  71453. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71454. /** Gets or sets value of Back button */
  71455. get: function () {
  71456. return this._buttonBack;
  71457. },
  71458. set: function (value) {
  71459. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71460. },
  71461. enumerable: true,
  71462. configurable: true
  71463. });
  71464. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71465. /** Gets or sets value of Left button */
  71466. get: function () {
  71467. return this._buttonLB;
  71468. },
  71469. set: function (value) {
  71470. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71471. },
  71472. enumerable: true,
  71473. configurable: true
  71474. });
  71475. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71476. /** Gets or sets value of Right button */
  71477. get: function () {
  71478. return this._buttonRB;
  71479. },
  71480. set: function (value) {
  71481. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71482. },
  71483. enumerable: true,
  71484. configurable: true
  71485. });
  71486. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71487. /** Gets or sets value of left stick */
  71488. get: function () {
  71489. return this._buttonLeftStick;
  71490. },
  71491. set: function (value) {
  71492. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71493. },
  71494. enumerable: true,
  71495. configurable: true
  71496. });
  71497. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71498. /** Gets or sets value of right stick */
  71499. get: function () {
  71500. return this._buttonRightStick;
  71501. },
  71502. set: function (value) {
  71503. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71504. },
  71505. enumerable: true,
  71506. configurable: true
  71507. });
  71508. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71509. /** Gets or sets value of DPad up */
  71510. get: function () {
  71511. return this._dPadUp;
  71512. },
  71513. set: function (value) {
  71514. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71515. },
  71516. enumerable: true,
  71517. configurable: true
  71518. });
  71519. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71520. /** Gets or sets value of DPad down */
  71521. get: function () {
  71522. return this._dPadDown;
  71523. },
  71524. set: function (value) {
  71525. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71526. },
  71527. enumerable: true,
  71528. configurable: true
  71529. });
  71530. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71531. /** Gets or sets value of DPad left */
  71532. get: function () {
  71533. return this._dPadLeft;
  71534. },
  71535. set: function (value) {
  71536. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71537. },
  71538. enumerable: true,
  71539. configurable: true
  71540. });
  71541. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71542. /** Gets or sets value of DPad right */
  71543. get: function () {
  71544. return this._dPadRight;
  71545. },
  71546. set: function (value) {
  71547. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71548. },
  71549. enumerable: true,
  71550. configurable: true
  71551. });
  71552. /**
  71553. * Force the gamepad to synchronize with device values
  71554. */
  71555. Xbox360Pad.prototype.update = function () {
  71556. _super.prototype.update.call(this);
  71557. if (this._isXboxOnePad) {
  71558. this.buttonA = this.browserGamepad.buttons[0].value;
  71559. this.buttonB = this.browserGamepad.buttons[1].value;
  71560. this.buttonX = this.browserGamepad.buttons[2].value;
  71561. this.buttonY = this.browserGamepad.buttons[3].value;
  71562. this.buttonLB = this.browserGamepad.buttons[4].value;
  71563. this.buttonRB = this.browserGamepad.buttons[5].value;
  71564. this.leftTrigger = this.browserGamepad.axes[2];
  71565. this.rightTrigger = this.browserGamepad.axes[5];
  71566. this.buttonBack = this.browserGamepad.buttons[9].value;
  71567. this.buttonStart = this.browserGamepad.buttons[8].value;
  71568. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71569. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71570. this.dPadUp = this.browserGamepad.buttons[11].value;
  71571. this.dPadDown = this.browserGamepad.buttons[12].value;
  71572. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71573. this.dPadRight = this.browserGamepad.buttons[14].value;
  71574. }
  71575. else {
  71576. this.buttonA = this.browserGamepad.buttons[0].value;
  71577. this.buttonB = this.browserGamepad.buttons[1].value;
  71578. this.buttonX = this.browserGamepad.buttons[2].value;
  71579. this.buttonY = this.browserGamepad.buttons[3].value;
  71580. this.buttonLB = this.browserGamepad.buttons[4].value;
  71581. this.buttonRB = this.browserGamepad.buttons[5].value;
  71582. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71583. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71584. this.buttonBack = this.browserGamepad.buttons[8].value;
  71585. this.buttonStart = this.browserGamepad.buttons[9].value;
  71586. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71587. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71588. this.dPadUp = this.browserGamepad.buttons[12].value;
  71589. this.dPadDown = this.browserGamepad.buttons[13].value;
  71590. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71591. this.dPadRight = this.browserGamepad.buttons[15].value;
  71592. }
  71593. };
  71594. Xbox360Pad.prototype.dispose = function () {
  71595. _super.prototype.dispose.call(this);
  71596. this.onButtonDownObservable.clear();
  71597. this.onButtonUpObservable.clear();
  71598. this.onPadDownObservable.clear();
  71599. this.onPadUpObservable.clear();
  71600. };
  71601. return Xbox360Pad;
  71602. }(BABYLON.Gamepad));
  71603. BABYLON.Xbox360Pad = Xbox360Pad;
  71604. })(BABYLON || (BABYLON = {}));
  71605. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71606. var BABYLON;
  71607. (function (BABYLON) {
  71608. /**
  71609. * Defines the types of pose enabled controllers that are supported
  71610. */
  71611. var PoseEnabledControllerType;
  71612. (function (PoseEnabledControllerType) {
  71613. /**
  71614. * HTC Vive
  71615. */
  71616. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71617. /**
  71618. * Oculus Rift
  71619. */
  71620. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71621. /**
  71622. * Windows mixed reality
  71623. */
  71624. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71625. /**
  71626. * Samsung gear VR
  71627. */
  71628. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71629. /**
  71630. * Google Daydream
  71631. */
  71632. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71633. /**
  71634. * Generic
  71635. */
  71636. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71637. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71638. /**
  71639. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71640. */
  71641. var PoseEnabledControllerHelper = /** @class */ (function () {
  71642. function PoseEnabledControllerHelper() {
  71643. }
  71644. /**
  71645. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71646. * @param vrGamepad the gamepad to initialized
  71647. * @returns a vr controller of the type the gamepad identified as
  71648. */
  71649. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71650. // Oculus Touch
  71651. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71652. return new BABYLON.OculusTouchController(vrGamepad);
  71653. }
  71654. // Windows Mixed Reality controllers
  71655. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71656. return new BABYLON.WindowsMotionController(vrGamepad);
  71657. }
  71658. // HTC Vive
  71659. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71660. return new BABYLON.ViveController(vrGamepad);
  71661. }
  71662. // Samsung/Oculus Gear VR or Oculus Go
  71663. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71664. return new BABYLON.GearVRController(vrGamepad);
  71665. }
  71666. // Google Daydream
  71667. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71668. return new BABYLON.DaydreamController(vrGamepad);
  71669. }
  71670. // Generic
  71671. else {
  71672. return new BABYLON.GenericController(vrGamepad);
  71673. }
  71674. };
  71675. return PoseEnabledControllerHelper;
  71676. }());
  71677. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71678. /**
  71679. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71680. */
  71681. var PoseEnabledController = /** @class */ (function (_super) {
  71682. __extends(PoseEnabledController, _super);
  71683. /**
  71684. * Creates a new PoseEnabledController from a gamepad
  71685. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71686. */
  71687. function PoseEnabledController(browserGamepad) {
  71688. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71689. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71690. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71691. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71692. /**
  71693. * The device position in babylon space
  71694. */
  71695. _this.devicePosition = BABYLON.Vector3.Zero();
  71696. /**
  71697. * The device rotation in babylon space
  71698. */
  71699. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71700. /**
  71701. * The scale factor of the device in babylon space
  71702. */
  71703. _this.deviceScaleFactor = 1;
  71704. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71705. /**
  71706. * Internal, matrix used to convert room space to babylon space
  71707. */
  71708. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71709. /**
  71710. * Node to be used when casting a ray from the controller
  71711. */
  71712. _this._pointingPoseNode = null;
  71713. _this._workingMatrix = BABYLON.Matrix.Identity();
  71714. /**
  71715. * @hidden
  71716. */
  71717. _this._meshAttachedObservable = new BABYLON.Observable();
  71718. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71719. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71720. _this.position = BABYLON.Vector3.Zero();
  71721. _this.rotationQuaternion = new BABYLON.Quaternion();
  71722. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71723. _this._calculatedRotation = new BABYLON.Quaternion();
  71724. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71725. return _this;
  71726. }
  71727. /**
  71728. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71729. */
  71730. PoseEnabledController.prototype.update = function () {
  71731. _super.prototype.update.call(this);
  71732. this._updatePoseAndMesh();
  71733. };
  71734. /**
  71735. * Updates only the pose device and mesh without doing any button event checking
  71736. */
  71737. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  71738. var pose = this.browserGamepad.pose;
  71739. this.updateFromDevice(pose);
  71740. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71741. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71742. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71743. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71744. if (this._mesh) {
  71745. this._mesh.position.copyFrom(this.devicePosition);
  71746. if (this._mesh.rotationQuaternion) {
  71747. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71748. }
  71749. }
  71750. };
  71751. /**
  71752. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71753. * @param poseData raw pose fromthe device
  71754. */
  71755. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71756. if (poseData) {
  71757. this.rawPose = poseData;
  71758. if (poseData.position) {
  71759. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71760. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71761. this._deviceRoomPosition.z *= -1;
  71762. }
  71763. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71764. this._calculatedPosition.addInPlace(this.position);
  71765. }
  71766. var pose = this.rawPose;
  71767. if (poseData.orientation && pose.orientation) {
  71768. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71769. if (this._mesh) {
  71770. if (this._mesh.getScene().useRightHandedSystem) {
  71771. this._deviceRoomRotationQuaternion.z *= -1;
  71772. this._deviceRoomRotationQuaternion.w *= -1;
  71773. }
  71774. else {
  71775. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71776. }
  71777. }
  71778. // if the camera is set, rotate to the camera's rotation
  71779. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71780. }
  71781. }
  71782. };
  71783. /**
  71784. * Attaches a mesh to the controller
  71785. * @param mesh the mesh to be attached
  71786. */
  71787. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71788. if (this._mesh) {
  71789. this._mesh.parent = null;
  71790. }
  71791. this._mesh = mesh;
  71792. if (this._poseControlledCamera) {
  71793. this._mesh.parent = this._poseControlledCamera;
  71794. }
  71795. if (!this._mesh.rotationQuaternion) {
  71796. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71797. }
  71798. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  71799. this._updatePoseAndMesh();
  71800. if (this._pointingPoseNode) {
  71801. var parents = [];
  71802. var obj = this._pointingPoseNode;
  71803. while (obj.parent) {
  71804. parents.push(obj.parent);
  71805. obj = obj.parent;
  71806. }
  71807. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71808. }
  71809. this._meshAttachedObservable.notifyObservers(mesh);
  71810. };
  71811. /**
  71812. * Attaches the controllers mesh to a camera
  71813. * @param camera the camera the mesh should be attached to
  71814. */
  71815. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71816. this._poseControlledCamera = camera;
  71817. if (this._mesh) {
  71818. this._mesh.parent = this._poseControlledCamera;
  71819. }
  71820. };
  71821. /**
  71822. * Disposes of the controller
  71823. */
  71824. PoseEnabledController.prototype.dispose = function () {
  71825. if (this._mesh) {
  71826. this._mesh.dispose();
  71827. }
  71828. this._mesh = null;
  71829. _super.prototype.dispose.call(this);
  71830. };
  71831. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71832. /**
  71833. * The mesh that is attached to the controller
  71834. */
  71835. get: function () {
  71836. return this._mesh;
  71837. },
  71838. enumerable: true,
  71839. configurable: true
  71840. });
  71841. /**
  71842. * Gets the ray of the controller in the direction the controller is pointing
  71843. * @param length the length the resulting ray should be
  71844. * @returns a ray in the direction the controller is pointing
  71845. */
  71846. PoseEnabledController.prototype.getForwardRay = function (length) {
  71847. if (length === void 0) { length = 100; }
  71848. if (!this.mesh) {
  71849. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71850. }
  71851. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71852. var origin = m.getTranslation();
  71853. var forward = new BABYLON.Vector3(0, 0, -1);
  71854. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71855. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71856. return new BABYLON.Ray(origin, direction, length);
  71857. };
  71858. /**
  71859. * Name of the child mesh that can be used to cast a ray from the controller
  71860. */
  71861. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71862. return PoseEnabledController;
  71863. }(BABYLON.Gamepad));
  71864. BABYLON.PoseEnabledController = PoseEnabledController;
  71865. })(BABYLON || (BABYLON = {}));
  71866. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71867. var BABYLON;
  71868. (function (BABYLON) {
  71869. /**
  71870. * Defines the WebVRController object that represents controllers tracked in 3D space
  71871. */
  71872. var WebVRController = /** @class */ (function (_super) {
  71873. __extends(WebVRController, _super);
  71874. /**
  71875. * Creates a new WebVRController from a gamepad
  71876. * @param vrGamepad the gamepad that the WebVRController should be created from
  71877. */
  71878. function WebVRController(vrGamepad) {
  71879. var _this = _super.call(this, vrGamepad) || this;
  71880. // Observables
  71881. /**
  71882. * Fired when the trigger state has changed
  71883. */
  71884. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71885. /**
  71886. * Fired when the main button state has changed
  71887. */
  71888. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71889. /**
  71890. * Fired when the secondary button state has changed
  71891. */
  71892. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71893. /**
  71894. * Fired when the pad state has changed
  71895. */
  71896. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71897. /**
  71898. * Fired when controllers stick values have changed
  71899. */
  71900. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71901. /**
  71902. * X and Y axis corrisponding to the controllers joystick
  71903. */
  71904. _this.pad = { x: 0, y: 0 };
  71905. // avoid GC, store state in a tmp object
  71906. _this._changes = {
  71907. pressChanged: false,
  71908. touchChanged: false,
  71909. valueChanged: false,
  71910. changed: false
  71911. };
  71912. _this._buttons = new Array(vrGamepad.buttons.length);
  71913. _this.hand = vrGamepad.hand;
  71914. return _this;
  71915. }
  71916. /**
  71917. * Fired when a controller button's state has changed
  71918. * @param callback the callback containing the button that was modified
  71919. */
  71920. WebVRController.prototype.onButtonStateChange = function (callback) {
  71921. this._onButtonStateChange = callback;
  71922. };
  71923. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71924. /**
  71925. * The default controller model for the controller
  71926. */
  71927. get: function () {
  71928. return this._defaultModel;
  71929. },
  71930. enumerable: true,
  71931. configurable: true
  71932. });
  71933. /**
  71934. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71935. */
  71936. WebVRController.prototype.update = function () {
  71937. _super.prototype.update.call(this);
  71938. for (var index = 0; index < this._buttons.length; index++) {
  71939. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71940. }
  71941. ;
  71942. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71943. this.pad.x = this.leftStick.x;
  71944. this.pad.y = this.leftStick.y;
  71945. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71946. }
  71947. };
  71948. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71949. if (!newState) {
  71950. newState = {
  71951. pressed: false,
  71952. touched: false,
  71953. value: 0
  71954. };
  71955. }
  71956. if (!currentState) {
  71957. this._buttons[buttonIndex] = {
  71958. pressed: newState.pressed,
  71959. touched: newState.touched,
  71960. value: newState.value
  71961. };
  71962. return;
  71963. }
  71964. this._checkChanges(newState, currentState);
  71965. if (this._changes.changed) {
  71966. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71967. this._handleButtonChange(buttonIndex, newState, this._changes);
  71968. }
  71969. this._buttons[buttonIndex].pressed = newState.pressed;
  71970. this._buttons[buttonIndex].touched = newState.touched;
  71971. // oculus triggers are never 0, thou not touched.
  71972. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71973. };
  71974. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71975. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71976. this._changes.touchChanged = newState.touched !== currentState.touched;
  71977. this._changes.valueChanged = newState.value !== currentState.value;
  71978. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71979. return this._changes;
  71980. };
  71981. /**
  71982. * Disposes of th webVRCOntroller
  71983. */
  71984. WebVRController.prototype.dispose = function () {
  71985. _super.prototype.dispose.call(this);
  71986. this.onTriggerStateChangedObservable.clear();
  71987. this.onMainButtonStateChangedObservable.clear();
  71988. this.onSecondaryButtonStateChangedObservable.clear();
  71989. this.onPadStateChangedObservable.clear();
  71990. this.onPadValuesChangedObservable.clear();
  71991. };
  71992. return WebVRController;
  71993. }(BABYLON.PoseEnabledController));
  71994. BABYLON.WebVRController = WebVRController;
  71995. })(BABYLON || (BABYLON = {}));
  71996. //# sourceMappingURL=babylon.webVRController.js.map
  71997. var BABYLON;
  71998. (function (BABYLON) {
  71999. /**
  72000. * Oculus Touch Controller
  72001. */
  72002. var OculusTouchController = /** @class */ (function (_super) {
  72003. __extends(OculusTouchController, _super);
  72004. /**
  72005. * Creates a new OculusTouchController from a gamepad
  72006. * @param vrGamepad the gamepad that the controller should be created from
  72007. */
  72008. function OculusTouchController(vrGamepad) {
  72009. var _this = _super.call(this, vrGamepad) || this;
  72010. /**
  72011. * Fired when the secondary trigger on this controller is modified
  72012. */
  72013. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72014. /**
  72015. * Fired when the thumb rest on this controller is modified
  72016. */
  72017. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72018. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72019. return _this;
  72020. }
  72021. /**
  72022. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72023. * @param scene scene in which to add meshes
  72024. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72025. */
  72026. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72027. var _this = this;
  72028. var meshName;
  72029. // Hand
  72030. if (this.hand === 'left') {
  72031. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72032. }
  72033. else { // Right is the default if no hand is specified
  72034. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72035. }
  72036. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72037. /*
  72038. Parent Mesh name: oculus_touch_left
  72039. - body
  72040. - trigger
  72041. - thumbstick
  72042. - grip
  72043. - button_y
  72044. - button_x
  72045. - button_enter
  72046. */
  72047. _this._defaultModel = newMeshes[1];
  72048. _this.attachToMesh(_this._defaultModel);
  72049. if (meshLoaded) {
  72050. meshLoaded(_this._defaultModel);
  72051. }
  72052. });
  72053. };
  72054. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72055. /**
  72056. * Fired when the A button on this controller is modified
  72057. */
  72058. get: function () {
  72059. if (this.hand === 'right') {
  72060. return this.onMainButtonStateChangedObservable;
  72061. }
  72062. else {
  72063. throw new Error('No A button on left hand');
  72064. }
  72065. },
  72066. enumerable: true,
  72067. configurable: true
  72068. });
  72069. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72070. /**
  72071. * Fired when the B button on this controller is modified
  72072. */
  72073. get: function () {
  72074. if (this.hand === 'right') {
  72075. return this.onSecondaryButtonStateChangedObservable;
  72076. }
  72077. else {
  72078. throw new Error('No B button on left hand');
  72079. }
  72080. },
  72081. enumerable: true,
  72082. configurable: true
  72083. });
  72084. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72085. /**
  72086. * Fired when the X button on this controller is modified
  72087. */
  72088. get: function () {
  72089. if (this.hand === 'left') {
  72090. return this.onMainButtonStateChangedObservable;
  72091. }
  72092. else {
  72093. throw new Error('No X button on right hand');
  72094. }
  72095. },
  72096. enumerable: true,
  72097. configurable: true
  72098. });
  72099. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72100. /**
  72101. * Fired when the Y button on this controller is modified
  72102. */
  72103. get: function () {
  72104. if (this.hand === 'left') {
  72105. return this.onSecondaryButtonStateChangedObservable;
  72106. }
  72107. else {
  72108. throw new Error('No Y button on right hand');
  72109. }
  72110. },
  72111. enumerable: true,
  72112. configurable: true
  72113. });
  72114. /**
  72115. * Called once for each button that changed state since the last frame
  72116. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72117. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72118. * 2) secondary trigger (same)
  72119. * 3) A (right) X (left), touch, pressed = value
  72120. * 4) B / Y
  72121. * 5) thumb rest
  72122. * @param buttonIdx Which button index changed
  72123. * @param state New state of the button
  72124. * @param changes Which properties on the state changed since last frame
  72125. */
  72126. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72127. var notifyObject = state; //{ state: state, changes: changes };
  72128. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72129. switch (buttonIdx) {
  72130. case 0:
  72131. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72132. return;
  72133. case 1: // index trigger
  72134. if (this._defaultModel) {
  72135. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72136. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72137. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72138. }
  72139. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72140. return;
  72141. case 2: // secondary trigger
  72142. if (this._defaultModel) {
  72143. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72144. }
  72145. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72146. return;
  72147. case 3:
  72148. if (this._defaultModel) {
  72149. if (notifyObject.pressed) {
  72150. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72151. }
  72152. else {
  72153. (this._defaultModel.getChildren()[1]).position.y = 0;
  72154. }
  72155. }
  72156. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72157. return;
  72158. case 4:
  72159. if (this._defaultModel) {
  72160. if (notifyObject.pressed) {
  72161. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72162. }
  72163. else {
  72164. (this._defaultModel.getChildren()[2]).position.y = 0;
  72165. }
  72166. }
  72167. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72168. return;
  72169. case 5:
  72170. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72171. return;
  72172. }
  72173. };
  72174. /**
  72175. * Base Url for the controller model.
  72176. */
  72177. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72178. /**
  72179. * File name for the left controller model.
  72180. */
  72181. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72182. /**
  72183. * File name for the right controller model.
  72184. */
  72185. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72186. return OculusTouchController;
  72187. }(BABYLON.WebVRController));
  72188. BABYLON.OculusTouchController = OculusTouchController;
  72189. })(BABYLON || (BABYLON = {}));
  72190. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72191. var BABYLON;
  72192. (function (BABYLON) {
  72193. /**
  72194. * Vive Controller
  72195. */
  72196. var ViveController = /** @class */ (function (_super) {
  72197. __extends(ViveController, _super);
  72198. /**
  72199. * Creates a new ViveController from a gamepad
  72200. * @param vrGamepad the gamepad that the controller should be created from
  72201. */
  72202. function ViveController(vrGamepad) {
  72203. var _this = _super.call(this, vrGamepad) || this;
  72204. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72205. _this._invertLeftStickY = true;
  72206. return _this;
  72207. }
  72208. /**
  72209. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72210. * @param scene scene in which to add meshes
  72211. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72212. */
  72213. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72214. var _this = this;
  72215. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72216. /*
  72217. Parent Mesh name: ViveWand
  72218. - body
  72219. - r_gripper
  72220. - l_gripper
  72221. - menu_button
  72222. - system_button
  72223. - trackpad
  72224. - trigger
  72225. - LED
  72226. */
  72227. _this._defaultModel = newMeshes[1];
  72228. _this.attachToMesh(_this._defaultModel);
  72229. if (meshLoaded) {
  72230. meshLoaded(_this._defaultModel);
  72231. }
  72232. });
  72233. };
  72234. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72235. /**
  72236. * Fired when the left button on this controller is modified
  72237. */
  72238. get: function () {
  72239. return this.onMainButtonStateChangedObservable;
  72240. },
  72241. enumerable: true,
  72242. configurable: true
  72243. });
  72244. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72245. /**
  72246. * Fired when the right button on this controller is modified
  72247. */
  72248. get: function () {
  72249. return this.onMainButtonStateChangedObservable;
  72250. },
  72251. enumerable: true,
  72252. configurable: true
  72253. });
  72254. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72255. /**
  72256. * Fired when the menu button on this controller is modified
  72257. */
  72258. get: function () {
  72259. return this.onSecondaryButtonStateChangedObservable;
  72260. },
  72261. enumerable: true,
  72262. configurable: true
  72263. });
  72264. /**
  72265. * Called once for each button that changed state since the last frame
  72266. * Vive mapping:
  72267. * 0: touchpad
  72268. * 1: trigger
  72269. * 2: left AND right buttons
  72270. * 3: menu button
  72271. * @param buttonIdx Which button index changed
  72272. * @param state New state of the button
  72273. * @param changes Which properties on the state changed since last frame
  72274. */
  72275. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72276. var notifyObject = state; //{ state: state, changes: changes };
  72277. switch (buttonIdx) {
  72278. case 0:
  72279. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72280. return;
  72281. case 1: // index trigger
  72282. if (this._defaultModel) {
  72283. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72284. }
  72285. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72286. return;
  72287. case 2: // left AND right button
  72288. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72289. return;
  72290. case 3:
  72291. if (this._defaultModel) {
  72292. if (notifyObject.pressed) {
  72293. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72294. }
  72295. else {
  72296. (this._defaultModel.getChildren()[2]).position.y = 0;
  72297. }
  72298. }
  72299. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72300. return;
  72301. }
  72302. };
  72303. /**
  72304. * Base Url for the controller model.
  72305. */
  72306. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72307. /**
  72308. * File name for the controller model.
  72309. */
  72310. ViveController.MODEL_FILENAME = 'wand.babylon';
  72311. return ViveController;
  72312. }(BABYLON.WebVRController));
  72313. BABYLON.ViveController = ViveController;
  72314. })(BABYLON || (BABYLON = {}));
  72315. //# sourceMappingURL=babylon.viveController.js.map
  72316. var BABYLON;
  72317. (function (BABYLON) {
  72318. /**
  72319. * Generic Controller
  72320. */
  72321. var GenericController = /** @class */ (function (_super) {
  72322. __extends(GenericController, _super);
  72323. /**
  72324. * Creates a new GenericController from a gamepad
  72325. * @param vrGamepad the gamepad that the controller should be created from
  72326. */
  72327. function GenericController(vrGamepad) {
  72328. return _super.call(this, vrGamepad) || this;
  72329. }
  72330. /**
  72331. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72332. * @param scene scene in which to add meshes
  72333. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72334. */
  72335. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72336. var _this = this;
  72337. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72338. _this._defaultModel = newMeshes[1];
  72339. _this.attachToMesh(_this._defaultModel);
  72340. if (meshLoaded) {
  72341. meshLoaded(_this._defaultModel);
  72342. }
  72343. });
  72344. };
  72345. /**
  72346. * Called once for each button that changed state since the last frame
  72347. * @param buttonIdx Which button index changed
  72348. * @param state New state of the button
  72349. * @param changes Which properties on the state changed since last frame
  72350. */
  72351. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72352. console.log("Button id: " + buttonIdx + "state: ");
  72353. console.dir(state);
  72354. };
  72355. /**
  72356. * Base Url for the controller model.
  72357. */
  72358. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72359. /**
  72360. * File name for the controller model.
  72361. */
  72362. GenericController.MODEL_FILENAME = 'generic.babylon';
  72363. return GenericController;
  72364. }(BABYLON.WebVRController));
  72365. BABYLON.GenericController = GenericController;
  72366. })(BABYLON || (BABYLON = {}));
  72367. //# sourceMappingURL=babylon.genericController.js.map
  72368. var BABYLON;
  72369. (function (BABYLON) {
  72370. /**
  72371. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72372. */
  72373. var LoadedMeshInfo = /** @class */ (function () {
  72374. function LoadedMeshInfo() {
  72375. /**
  72376. * Map of the button meshes contained in the controller
  72377. */
  72378. this.buttonMeshes = {};
  72379. /**
  72380. * Map of the axis meshes contained in the controller
  72381. */
  72382. this.axisMeshes = {};
  72383. }
  72384. return LoadedMeshInfo;
  72385. }());
  72386. /**
  72387. * Defines the WindowsMotionController object that the state of the windows motion controller
  72388. */
  72389. var WindowsMotionController = /** @class */ (function (_super) {
  72390. __extends(WindowsMotionController, _super);
  72391. /**
  72392. * Creates a new WindowsMotionController from a gamepad
  72393. * @param vrGamepad the gamepad that the controller should be created from
  72394. */
  72395. function WindowsMotionController(vrGamepad) {
  72396. var _this = _super.call(this, vrGamepad) || this;
  72397. _this._mapping = {
  72398. // Semantic button names
  72399. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72400. // A mapping of the button name to glTF model node name
  72401. // that should be transformed by button value.
  72402. buttonMeshNames: {
  72403. 'trigger': 'SELECT',
  72404. 'menu': 'MENU',
  72405. 'grip': 'GRASP',
  72406. 'thumbstick': 'THUMBSTICK_PRESS',
  72407. 'trackpad': 'TOUCHPAD_PRESS'
  72408. },
  72409. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72410. buttonObservableNames: {
  72411. 'trigger': 'onTriggerStateChangedObservable',
  72412. 'menu': 'onSecondaryButtonStateChangedObservable',
  72413. 'grip': 'onMainButtonStateChangedObservable',
  72414. 'thumbstick': 'onPadStateChangedObservable',
  72415. 'trackpad': 'onTrackpadChangedObservable'
  72416. },
  72417. // A mapping of the axis name to glTF model node name
  72418. // that should be transformed by axis value.
  72419. // This array mirrors the browserGamepad.axes array, such that
  72420. // the mesh corresponding to axis 0 is in this array index 0.
  72421. axisMeshNames: [
  72422. 'THUMBSTICK_X',
  72423. 'THUMBSTICK_Y',
  72424. 'TOUCHPAD_TOUCH_X',
  72425. 'TOUCHPAD_TOUCH_Y'
  72426. ],
  72427. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72428. };
  72429. /**
  72430. * Fired when the trackpad on this controller is clicked
  72431. */
  72432. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72433. /**
  72434. * Fired when the trackpad on this controller is modified
  72435. */
  72436. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72437. /**
  72438. * The current x and y values of this controller's trackpad
  72439. */
  72440. _this.trackpad = { x: 0, y: 0 };
  72441. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72442. _this._loadedMeshInfo = null;
  72443. return _this;
  72444. }
  72445. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72446. /**
  72447. * Fired when the trigger on this controller is modified
  72448. */
  72449. get: function () {
  72450. return this.onTriggerStateChangedObservable;
  72451. },
  72452. enumerable: true,
  72453. configurable: true
  72454. });
  72455. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72456. /**
  72457. * Fired when the menu button on this controller is modified
  72458. */
  72459. get: function () {
  72460. return this.onSecondaryButtonStateChangedObservable;
  72461. },
  72462. enumerable: true,
  72463. configurable: true
  72464. });
  72465. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72466. /**
  72467. * Fired when the grip button on this controller is modified
  72468. */
  72469. get: function () {
  72470. return this.onMainButtonStateChangedObservable;
  72471. },
  72472. enumerable: true,
  72473. configurable: true
  72474. });
  72475. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72476. /**
  72477. * Fired when the thumbstick button on this controller is modified
  72478. */
  72479. get: function () {
  72480. return this.onPadStateChangedObservable;
  72481. },
  72482. enumerable: true,
  72483. configurable: true
  72484. });
  72485. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72486. /**
  72487. * Fired when the touchpad button on this controller is modified
  72488. */
  72489. get: function () {
  72490. return this.onTrackpadChangedObservable;
  72491. },
  72492. enumerable: true,
  72493. configurable: true
  72494. });
  72495. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72496. /**
  72497. * Fired when the touchpad values on this controller are modified
  72498. */
  72499. get: function () {
  72500. return this.onTrackpadValuesChangedObservable;
  72501. },
  72502. enumerable: true,
  72503. configurable: true
  72504. });
  72505. WindowsMotionController.prototype._updateTrackpad = function () {
  72506. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72507. this.trackpad.x = this.browserGamepad["axes"][2];
  72508. this.trackpad.y = this.browserGamepad["axes"][3];
  72509. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72510. }
  72511. };
  72512. /**
  72513. * Called once per frame by the engine.
  72514. */
  72515. WindowsMotionController.prototype.update = function () {
  72516. _super.prototype.update.call(this);
  72517. if (this.browserGamepad.axes) {
  72518. this._updateTrackpad();
  72519. // Only need to animate axes if there is a loaded mesh
  72520. if (this._loadedMeshInfo) {
  72521. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72522. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72523. }
  72524. }
  72525. }
  72526. };
  72527. /**
  72528. * Called once for each button that changed state since the last frame
  72529. * @param buttonIdx Which button index changed
  72530. * @param state New state of the button
  72531. * @param changes Which properties on the state changed since last frame
  72532. */
  72533. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72534. var buttonName = this._mapping.buttons[buttonIdx];
  72535. if (!buttonName) {
  72536. return;
  72537. }
  72538. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72539. this._updateTrackpad();
  72540. // Only emit events for buttons that we know how to map from index to name
  72541. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72542. if (observable) {
  72543. observable.notifyObservers(state);
  72544. }
  72545. this._lerpButtonTransform(buttonName, state.value);
  72546. };
  72547. /**
  72548. * Moves the buttons on the controller mesh based on their current state
  72549. * @param buttonName the name of the button to move
  72550. * @param buttonValue the value of the button which determines the buttons new position
  72551. */
  72552. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72553. // If there is no loaded mesh, there is nothing to transform.
  72554. if (!this._loadedMeshInfo) {
  72555. return;
  72556. }
  72557. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72558. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72559. return;
  72560. }
  72561. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72562. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72563. };
  72564. /**
  72565. * Moves the axis on the controller mesh based on its current state
  72566. * @param axis the index of the axis
  72567. * @param axisValue the value of the axis which determines the meshes new position
  72568. * @hidden
  72569. */
  72570. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72571. if (!this._loadedMeshInfo) {
  72572. return;
  72573. }
  72574. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72575. if (!meshInfo) {
  72576. return;
  72577. }
  72578. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72579. return;
  72580. }
  72581. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72582. var lerpValue = axisValue * 0.5 + 0.5;
  72583. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72584. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72585. };
  72586. /**
  72587. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72588. * @param scene scene in which to add meshes
  72589. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72590. */
  72591. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72592. var _this = this;
  72593. if (forceDefault === void 0) { forceDefault = false; }
  72594. var path;
  72595. var filename;
  72596. // Checking if GLB loader is present
  72597. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72598. // Determine the device specific folder based on the ID suffix
  72599. var device = 'default';
  72600. if (this.id && !forceDefault) {
  72601. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72602. device = ((match && match[0]) || device);
  72603. }
  72604. // Hand
  72605. if (this.hand === 'left') {
  72606. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72607. }
  72608. else { // Right is the default if no hand is specified
  72609. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72610. }
  72611. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72612. }
  72613. else {
  72614. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72615. path = BABYLON.GenericController.MODEL_BASE_URL;
  72616. filename = BABYLON.GenericController.MODEL_FILENAME;
  72617. }
  72618. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72619. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72620. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72621. if (!_this._loadedMeshInfo) {
  72622. return;
  72623. }
  72624. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72625. _this.attachToMesh(_this._defaultModel);
  72626. if (meshLoaded) {
  72627. meshLoaded(_this._defaultModel);
  72628. }
  72629. }, null, function (scene, message) {
  72630. BABYLON.Tools.Log(message);
  72631. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72632. if (!forceDefault) {
  72633. _this.initControllerMesh(scene, meshLoaded, true);
  72634. }
  72635. });
  72636. };
  72637. /**
  72638. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72639. * can be transformed by button presses and axes values, based on this._mapping.
  72640. *
  72641. * @param scene scene in which the meshes exist
  72642. * @param meshes list of meshes that make up the controller model to process
  72643. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72644. */
  72645. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72646. var loadedMeshInfo = null;
  72647. // Create a new mesh to contain the glTF hierarchy
  72648. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72649. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72650. var childMesh = null;
  72651. for (var i = 0; i < meshes.length; i++) {
  72652. var mesh = meshes[i];
  72653. if (!mesh.parent) {
  72654. // Exclude controller meshes from picking results
  72655. mesh.isPickable = false;
  72656. // Handle root node, attach to the new parentMesh
  72657. childMesh = mesh;
  72658. break;
  72659. }
  72660. }
  72661. if (childMesh) {
  72662. childMesh.setParent(parentMesh);
  72663. // Create our mesh info. Note that this method will always return non-null.
  72664. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72665. }
  72666. else {
  72667. BABYLON.Tools.Warn('Could not find root node in model file.');
  72668. }
  72669. return loadedMeshInfo;
  72670. };
  72671. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72672. var loadedMeshInfo = new LoadedMeshInfo();
  72673. var i;
  72674. loadedMeshInfo.rootNode = rootNode;
  72675. // Reset the caches
  72676. loadedMeshInfo.buttonMeshes = {};
  72677. loadedMeshInfo.axisMeshes = {};
  72678. // Button Meshes
  72679. for (i = 0; i < this._mapping.buttons.length; i++) {
  72680. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72681. if (!buttonMeshName) {
  72682. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72683. continue;
  72684. }
  72685. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72686. if (!buttonMesh) {
  72687. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72688. continue;
  72689. }
  72690. var buttonMeshInfo = {
  72691. index: i,
  72692. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72693. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72694. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72695. };
  72696. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72697. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72698. }
  72699. else {
  72700. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72701. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72702. '(VALUE: ' + !!buttonMeshInfo.value +
  72703. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72704. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72705. ')');
  72706. }
  72707. }
  72708. // Axis Meshes
  72709. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72710. var axisMeshName = this._mapping.axisMeshNames[i];
  72711. if (!axisMeshName) {
  72712. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72713. continue;
  72714. }
  72715. var axisMesh = getChildByName(rootNode, axisMeshName);
  72716. if (!axisMesh) {
  72717. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72718. continue;
  72719. }
  72720. var axisMeshInfo = {
  72721. index: i,
  72722. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72723. min: getImmediateChildByName(axisMesh, 'MIN'),
  72724. max: getImmediateChildByName(axisMesh, 'MAX')
  72725. };
  72726. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72727. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72728. }
  72729. else {
  72730. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72731. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72732. '(VALUE: ' + !!axisMeshInfo.value +
  72733. ', MIN: ' + !!axisMeshInfo.min +
  72734. ', MAX:' + !!axisMeshInfo.max +
  72735. ')');
  72736. }
  72737. }
  72738. // Pointing Ray
  72739. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72740. if (!loadedMeshInfo.pointingPoseNode) {
  72741. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72742. }
  72743. else {
  72744. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72745. }
  72746. return loadedMeshInfo;
  72747. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72748. function getChildByName(node, name) {
  72749. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72750. }
  72751. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72752. function getImmediateChildByName(node, name) {
  72753. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72754. }
  72755. };
  72756. /**
  72757. * Gets the ray of the controller in the direction the controller is pointing
  72758. * @param length the length the resulting ray should be
  72759. * @returns a ray in the direction the controller is pointing
  72760. */
  72761. WindowsMotionController.prototype.getForwardRay = function (length) {
  72762. if (length === void 0) { length = 100; }
  72763. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72764. return _super.prototype.getForwardRay.call(this, length);
  72765. }
  72766. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72767. var origin = m.getTranslation();
  72768. var forward = new BABYLON.Vector3(0, 0, -1);
  72769. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72770. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72771. return new BABYLON.Ray(origin, direction, length);
  72772. };
  72773. /**
  72774. * Disposes of the controller
  72775. */
  72776. WindowsMotionController.prototype.dispose = function () {
  72777. _super.prototype.dispose.call(this);
  72778. this.onTrackpadChangedObservable.clear();
  72779. };
  72780. /**
  72781. * The base url used to load the left and right controller models
  72782. */
  72783. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72784. /**
  72785. * The name of the left controller model file
  72786. */
  72787. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72788. /**
  72789. * The name of the right controller model file
  72790. */
  72791. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72792. /**
  72793. * The controller name prefix for this controller type
  72794. */
  72795. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72796. /**
  72797. * The controller id pattern for this controller type
  72798. */
  72799. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72800. return WindowsMotionController;
  72801. }(BABYLON.WebVRController));
  72802. BABYLON.WindowsMotionController = WindowsMotionController;
  72803. })(BABYLON || (BABYLON = {}));
  72804. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72805. var BABYLON;
  72806. (function (BABYLON) {
  72807. /**
  72808. * Gear VR Controller
  72809. */
  72810. var GearVRController = /** @class */ (function (_super) {
  72811. __extends(GearVRController, _super);
  72812. /**
  72813. * Creates a new GearVRController from a gamepad
  72814. * @param vrGamepad the gamepad that the controller should be created from
  72815. */
  72816. function GearVRController(vrGamepad) {
  72817. var _this = _super.call(this, vrGamepad) || this;
  72818. _this._buttonIndexToObservableNameMap = [
  72819. 'onTrackpadChangedObservable',
  72820. 'onTriggerStateChangedObservable' // Trigger
  72821. ];
  72822. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72823. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72824. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72825. return _this;
  72826. }
  72827. /**
  72828. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72829. * @param scene scene in which to add meshes
  72830. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72831. */
  72832. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72833. var _this = this;
  72834. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72835. _this._defaultModel = newMeshes[1];
  72836. _this.attachToMesh(_this._defaultModel);
  72837. if (meshLoaded) {
  72838. meshLoaded(_this._defaultModel);
  72839. }
  72840. });
  72841. };
  72842. /**
  72843. * Called once for each button that changed state since the last frame
  72844. * @param buttonIdx Which button index changed
  72845. * @param state New state of the button
  72846. * @param changes Which properties on the state changed since last frame
  72847. */
  72848. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72849. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72850. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72851. // Only emit events for buttons that we know how to map from index to observable
  72852. var observable = this[observableName];
  72853. if (observable) {
  72854. observable.notifyObservers(state);
  72855. }
  72856. }
  72857. };
  72858. /**
  72859. * Base Url for the controller model.
  72860. */
  72861. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72862. /**
  72863. * File name for the controller model.
  72864. */
  72865. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72866. /**
  72867. * Gamepad Id prefix used to identify this controller.
  72868. */
  72869. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72870. return GearVRController;
  72871. }(BABYLON.WebVRController));
  72872. BABYLON.GearVRController = GearVRController;
  72873. })(BABYLON || (BABYLON = {}));
  72874. //# sourceMappingURL=babylon.gearVRController.js.map
  72875. var BABYLON;
  72876. (function (BABYLON) {
  72877. /**
  72878. * Google Daydream controller
  72879. */
  72880. var DaydreamController = /** @class */ (function (_super) {
  72881. __extends(DaydreamController, _super);
  72882. /**
  72883. * Creates a new DaydreamController from a gamepad
  72884. * @param vrGamepad the gamepad that the controller should be created from
  72885. */
  72886. function DaydreamController(vrGamepad) {
  72887. var _this = _super.call(this, vrGamepad) || this;
  72888. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72889. return _this;
  72890. }
  72891. /**
  72892. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72893. * @param scene scene in which to add meshes
  72894. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72895. */
  72896. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72897. var _this = this;
  72898. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72899. _this._defaultModel = newMeshes[1];
  72900. _this.attachToMesh(_this._defaultModel);
  72901. if (meshLoaded) {
  72902. meshLoaded(_this._defaultModel);
  72903. }
  72904. });
  72905. };
  72906. /**
  72907. * Called once for each button that changed state since the last frame
  72908. * @param buttonIdx Which button index changed
  72909. * @param state New state of the button
  72910. * @param changes Which properties on the state changed since last frame
  72911. */
  72912. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72913. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72914. if (buttonIdx === 0) {
  72915. var observable = this.onTriggerStateChangedObservable;
  72916. if (observable) {
  72917. observable.notifyObservers(state);
  72918. }
  72919. }
  72920. else {
  72921. // If the app or home buttons are ever made available
  72922. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72923. }
  72924. };
  72925. /**
  72926. * Base Url for the controller model.
  72927. */
  72928. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72929. /**
  72930. * File name for the controller model.
  72931. */
  72932. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72933. /**
  72934. * Gamepad Id prefix used to identify Daydream Controller.
  72935. */
  72936. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72937. return DaydreamController;
  72938. }(BABYLON.WebVRController));
  72939. BABYLON.DaydreamController = DaydreamController;
  72940. })(BABYLON || (BABYLON = {}));
  72941. //# sourceMappingURL=babylon.daydreamController.js.map
  72942. var BABYLON;
  72943. (function (BABYLON) {
  72944. var FollowCamera = /** @class */ (function (_super) {
  72945. __extends(FollowCamera, _super);
  72946. function FollowCamera(name, position, scene, lockedTarget) {
  72947. if (lockedTarget === void 0) { lockedTarget = null; }
  72948. var _this = _super.call(this, name, position, scene) || this;
  72949. _this.radius = 12;
  72950. _this.rotationOffset = 0;
  72951. _this.heightOffset = 4;
  72952. _this.cameraAcceleration = 0.05;
  72953. _this.maxCameraSpeed = 20;
  72954. _this.lockedTarget = lockedTarget;
  72955. return _this;
  72956. }
  72957. FollowCamera.prototype.getRadians = function (degrees) {
  72958. return degrees * Math.PI / 180;
  72959. };
  72960. FollowCamera.prototype.follow = function (cameraTarget) {
  72961. if (!cameraTarget)
  72962. return;
  72963. var yRotation;
  72964. if (cameraTarget.rotationQuaternion) {
  72965. var rotMatrix = new BABYLON.Matrix();
  72966. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72967. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72968. }
  72969. else {
  72970. yRotation = cameraTarget.rotation.y;
  72971. }
  72972. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72973. var targetPosition = cameraTarget.getAbsolutePosition();
  72974. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72975. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72976. var dx = targetX - this.position.x;
  72977. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72978. var dz = (targetZ) - this.position.z;
  72979. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72980. var vy = dy * this.cameraAcceleration;
  72981. var vz = dz * this.cameraAcceleration * 2;
  72982. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72983. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72984. }
  72985. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72986. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72987. }
  72988. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72989. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72990. }
  72991. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72992. this.setTarget(targetPosition);
  72993. };
  72994. FollowCamera.prototype._checkInputs = function () {
  72995. _super.prototype._checkInputs.call(this);
  72996. if (this.lockedTarget) {
  72997. this.follow(this.lockedTarget);
  72998. }
  72999. };
  73000. FollowCamera.prototype.getClassName = function () {
  73001. return "FollowCamera";
  73002. };
  73003. __decorate([
  73004. BABYLON.serialize()
  73005. ], FollowCamera.prototype, "radius", void 0);
  73006. __decorate([
  73007. BABYLON.serialize()
  73008. ], FollowCamera.prototype, "rotationOffset", void 0);
  73009. __decorate([
  73010. BABYLON.serialize()
  73011. ], FollowCamera.prototype, "heightOffset", void 0);
  73012. __decorate([
  73013. BABYLON.serialize()
  73014. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73015. __decorate([
  73016. BABYLON.serialize()
  73017. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73018. __decorate([
  73019. BABYLON.serializeAsMeshReference("lockedTargetId")
  73020. ], FollowCamera.prototype, "lockedTarget", void 0);
  73021. return FollowCamera;
  73022. }(BABYLON.TargetCamera));
  73023. BABYLON.FollowCamera = FollowCamera;
  73024. var ArcFollowCamera = /** @class */ (function (_super) {
  73025. __extends(ArcFollowCamera, _super);
  73026. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73027. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73028. _this.alpha = alpha;
  73029. _this.beta = beta;
  73030. _this.radius = radius;
  73031. _this.target = target;
  73032. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73033. _this.follow();
  73034. return _this;
  73035. }
  73036. ArcFollowCamera.prototype.follow = function () {
  73037. if (!this.target) {
  73038. return;
  73039. }
  73040. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73041. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73042. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73043. var targetPosition = this.target.getAbsolutePosition();
  73044. this.position = targetPosition.add(this._cartesianCoordinates);
  73045. this.setTarget(targetPosition);
  73046. };
  73047. ArcFollowCamera.prototype._checkInputs = function () {
  73048. _super.prototype._checkInputs.call(this);
  73049. this.follow();
  73050. };
  73051. ArcFollowCamera.prototype.getClassName = function () {
  73052. return "ArcFollowCamera";
  73053. };
  73054. return ArcFollowCamera;
  73055. }(BABYLON.TargetCamera));
  73056. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73057. })(BABYLON || (BABYLON = {}));
  73058. //# sourceMappingURL=babylon.followCamera.js.map
  73059. var BABYLON;
  73060. (function (BABYLON) {
  73061. // We're mainly based on the logic defined into the FreeCamera code
  73062. var UniversalCamera = /** @class */ (function (_super) {
  73063. __extends(UniversalCamera, _super);
  73064. //-- end properties for backward compatibility for inputs
  73065. function UniversalCamera(name, position, scene) {
  73066. var _this = _super.call(this, name, position, scene) || this;
  73067. _this.inputs.addGamepad();
  73068. return _this;
  73069. }
  73070. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73071. //-- Begin properties for backward compatibility for inputs
  73072. get: function () {
  73073. var gamepad = this.inputs.attached["gamepad"];
  73074. if (gamepad)
  73075. return gamepad.gamepadAngularSensibility;
  73076. return 0;
  73077. },
  73078. set: function (value) {
  73079. var gamepad = this.inputs.attached["gamepad"];
  73080. if (gamepad)
  73081. gamepad.gamepadAngularSensibility = value;
  73082. },
  73083. enumerable: true,
  73084. configurable: true
  73085. });
  73086. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73087. get: function () {
  73088. var gamepad = this.inputs.attached["gamepad"];
  73089. if (gamepad)
  73090. return gamepad.gamepadMoveSensibility;
  73091. return 0;
  73092. },
  73093. set: function (value) {
  73094. var gamepad = this.inputs.attached["gamepad"];
  73095. if (gamepad)
  73096. gamepad.gamepadMoveSensibility = value;
  73097. },
  73098. enumerable: true,
  73099. configurable: true
  73100. });
  73101. UniversalCamera.prototype.getClassName = function () {
  73102. return "UniversalCamera";
  73103. };
  73104. return UniversalCamera;
  73105. }(BABYLON.TouchCamera));
  73106. BABYLON.UniversalCamera = UniversalCamera;
  73107. })(BABYLON || (BABYLON = {}));
  73108. //# sourceMappingURL=babylon.universalCamera.js.map
  73109. var BABYLON;
  73110. (function (BABYLON) {
  73111. // We're mainly based on the logic defined into the FreeCamera code
  73112. var GamepadCamera = /** @class */ (function (_super) {
  73113. __extends(GamepadCamera, _super);
  73114. //-- end properties for backward compatibility for inputs
  73115. function GamepadCamera(name, position, scene) {
  73116. return _super.call(this, name, position, scene) || this;
  73117. }
  73118. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73119. //-- Begin properties for backward compatibility for inputs
  73120. get: function () {
  73121. var gamepad = this.inputs.attached["gamepad"];
  73122. if (gamepad)
  73123. return gamepad.gamepadAngularSensibility;
  73124. return 0;
  73125. },
  73126. set: function (value) {
  73127. var gamepad = this.inputs.attached["gamepad"];
  73128. if (gamepad)
  73129. gamepad.gamepadAngularSensibility = value;
  73130. },
  73131. enumerable: true,
  73132. configurable: true
  73133. });
  73134. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73135. get: function () {
  73136. var gamepad = this.inputs.attached["gamepad"];
  73137. if (gamepad)
  73138. return gamepad.gamepadMoveSensibility;
  73139. return 0;
  73140. },
  73141. set: function (value) {
  73142. var gamepad = this.inputs.attached["gamepad"];
  73143. if (gamepad)
  73144. gamepad.gamepadMoveSensibility = value;
  73145. },
  73146. enumerable: true,
  73147. configurable: true
  73148. });
  73149. GamepadCamera.prototype.getClassName = function () {
  73150. return "GamepadCamera";
  73151. };
  73152. return GamepadCamera;
  73153. }(BABYLON.UniversalCamera));
  73154. BABYLON.GamepadCamera = GamepadCamera;
  73155. })(BABYLON || (BABYLON = {}));
  73156. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73157. var BABYLON;
  73158. (function (BABYLON) {
  73159. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73160. function PostProcessRenderPipelineManager() {
  73161. this._renderPipelines = {};
  73162. }
  73163. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73164. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73165. };
  73166. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73167. if (unique === void 0) { unique = false; }
  73168. var renderPipeline = this._renderPipelines[renderPipelineName];
  73169. if (!renderPipeline) {
  73170. return;
  73171. }
  73172. renderPipeline._attachCameras(cameras, unique);
  73173. };
  73174. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73175. var renderPipeline = this._renderPipelines[renderPipelineName];
  73176. if (!renderPipeline) {
  73177. return;
  73178. }
  73179. renderPipeline._detachCameras(cameras);
  73180. };
  73181. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73182. var renderPipeline = this._renderPipelines[renderPipelineName];
  73183. if (!renderPipeline) {
  73184. return;
  73185. }
  73186. renderPipeline._enableEffect(renderEffectName, cameras);
  73187. };
  73188. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73189. var renderPipeline = this._renderPipelines[renderPipelineName];
  73190. if (!renderPipeline) {
  73191. return;
  73192. }
  73193. renderPipeline._disableEffect(renderEffectName, cameras);
  73194. };
  73195. PostProcessRenderPipelineManager.prototype.update = function () {
  73196. for (var renderPipelineName in this._renderPipelines) {
  73197. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73198. var pipeline = this._renderPipelines[renderPipelineName];
  73199. if (!pipeline.isSupported) {
  73200. pipeline.dispose();
  73201. delete this._renderPipelines[renderPipelineName];
  73202. }
  73203. else {
  73204. pipeline._update();
  73205. }
  73206. }
  73207. }
  73208. };
  73209. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73210. for (var renderPipelineName in this._renderPipelines) {
  73211. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73212. var pipeline = this._renderPipelines[renderPipelineName];
  73213. pipeline._rebuild();
  73214. }
  73215. }
  73216. };
  73217. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73218. for (var renderPipelineName in this._renderPipelines) {
  73219. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73220. var pipeline = this._renderPipelines[renderPipelineName];
  73221. pipeline.dispose();
  73222. }
  73223. }
  73224. };
  73225. return PostProcessRenderPipelineManager;
  73226. }());
  73227. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73228. })(BABYLON || (BABYLON = {}));
  73229. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73230. var BABYLON;
  73231. (function (BABYLON) {
  73232. /**
  73233. * This represents a set of one or more post processes in Babylon.
  73234. * A post process can be used to apply a shader to a texture after it is rendered.
  73235. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73236. */
  73237. var PostProcessRenderEffect = /** @class */ (function () {
  73238. /**
  73239. * Instantiates a post process render effect.
  73240. * A post process can be used to apply a shader to a texture after it is rendered.
  73241. * @param engine The engine the effect is tied to
  73242. * @param name The name of the effect
  73243. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73244. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73245. */
  73246. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73247. this._name = name;
  73248. this._singleInstance = singleInstance || true;
  73249. this._getPostProcesses = getPostProcesses;
  73250. this._cameras = {};
  73251. this._indicesForCamera = {};
  73252. this._postProcesses = {};
  73253. }
  73254. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73255. /**
  73256. * Checks if all the post processes in the effect are supported.
  73257. */
  73258. get: function () {
  73259. for (var index in this._postProcesses) {
  73260. if (this._postProcesses.hasOwnProperty(index)) {
  73261. var pps = this._postProcesses[index];
  73262. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73263. if (!pps[ppIndex].isSupported) {
  73264. return false;
  73265. }
  73266. }
  73267. }
  73268. }
  73269. return true;
  73270. },
  73271. enumerable: true,
  73272. configurable: true
  73273. });
  73274. /**
  73275. * Updates the current state of the effect
  73276. */
  73277. PostProcessRenderEffect.prototype._update = function () {
  73278. };
  73279. /**
  73280. * Attaches the effect on cameras
  73281. * @param cameras The camera to attach to.
  73282. */
  73283. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73284. var _this = this;
  73285. var cameraKey;
  73286. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73287. if (!cams) {
  73288. return;
  73289. }
  73290. for (var i = 0; i < cams.length; i++) {
  73291. var camera = cams[i];
  73292. var cameraName = camera.name;
  73293. if (this._singleInstance) {
  73294. cameraKey = 0;
  73295. }
  73296. else {
  73297. cameraKey = cameraName;
  73298. }
  73299. if (!this._postProcesses[cameraKey]) {
  73300. var postProcess = this._getPostProcesses();
  73301. if (postProcess) {
  73302. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73303. }
  73304. }
  73305. if (!this._indicesForCamera[cameraName]) {
  73306. this._indicesForCamera[cameraName] = [];
  73307. }
  73308. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73309. var index = camera.attachPostProcess(postProcess);
  73310. _this._indicesForCamera[cameraName].push(index);
  73311. });
  73312. if (!this._cameras[cameraName]) {
  73313. this._cameras[cameraName] = camera;
  73314. }
  73315. }
  73316. };
  73317. /**
  73318. * Detatches the effect on cameras
  73319. * @param cameras The camera to detatch from.
  73320. */
  73321. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73322. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73323. if (!cams) {
  73324. return;
  73325. }
  73326. for (var i = 0; i < cams.length; i++) {
  73327. var camera = cams[i];
  73328. var cameraName = camera.name;
  73329. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73330. camera.detachPostProcess(postProcess);
  73331. });
  73332. if (this._cameras[cameraName]) {
  73333. //this._indicesForCamera.splice(index, 1);
  73334. this._cameras[cameraName] = null;
  73335. }
  73336. }
  73337. };
  73338. /**
  73339. * Enables the effect on given cameras
  73340. * @param cameras The camera to enable.
  73341. */
  73342. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73343. var _this = this;
  73344. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73345. if (!cams) {
  73346. return;
  73347. }
  73348. for (var i = 0; i < cams.length; i++) {
  73349. var camera = cams[i];
  73350. var cameraName = camera.name;
  73351. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73352. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73353. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73354. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73355. });
  73356. }
  73357. }
  73358. }
  73359. };
  73360. /**
  73361. * Disables the effect on the given cameras
  73362. * @param cameras The camera to disable.
  73363. */
  73364. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73365. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73366. if (!cams) {
  73367. return;
  73368. }
  73369. for (var i = 0; i < cams.length; i++) {
  73370. var camera = cams[i];
  73371. var cameraName = camera.name;
  73372. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73373. camera.detachPostProcess(postProcess);
  73374. });
  73375. }
  73376. };
  73377. /**
  73378. * Gets a list of the post processes contained in the effect.
  73379. * @param camera The camera to get the post processes on.
  73380. * @returns The list of the post processes in the effect.
  73381. */
  73382. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73383. if (this._singleInstance) {
  73384. return this._postProcesses[0];
  73385. }
  73386. else {
  73387. if (!camera) {
  73388. return null;
  73389. }
  73390. return this._postProcesses[camera.name];
  73391. }
  73392. };
  73393. return PostProcessRenderEffect;
  73394. }());
  73395. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73396. })(BABYLON || (BABYLON = {}));
  73397. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73398. var BABYLON;
  73399. (function (BABYLON) {
  73400. var PostProcessRenderPipeline = /** @class */ (function () {
  73401. function PostProcessRenderPipeline(engine, name) {
  73402. this.engine = engine;
  73403. this._name = name;
  73404. this._renderEffects = {};
  73405. this._renderEffectsForIsolatedPass = new Array();
  73406. this._cameras = [];
  73407. }
  73408. PostProcessRenderPipeline.prototype.getClassName = function () {
  73409. return "PostProcessRenderPipeline";
  73410. };
  73411. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73412. get: function () {
  73413. for (var renderEffectName in this._renderEffects) {
  73414. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73415. if (!this._renderEffects[renderEffectName].isSupported) {
  73416. return false;
  73417. }
  73418. }
  73419. }
  73420. return true;
  73421. },
  73422. enumerable: true,
  73423. configurable: true
  73424. });
  73425. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73426. this._renderEffects[renderEffect._name] = renderEffect;
  73427. };
  73428. // private
  73429. PostProcessRenderPipeline.prototype._rebuild = function () {
  73430. };
  73431. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73432. var renderEffects = this._renderEffects[renderEffectName];
  73433. if (!renderEffects) {
  73434. return;
  73435. }
  73436. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73437. };
  73438. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73439. var renderEffects = this._renderEffects[renderEffectName];
  73440. if (!renderEffects) {
  73441. return;
  73442. }
  73443. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73444. };
  73445. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73446. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73447. if (!cams) {
  73448. return;
  73449. }
  73450. var indicesToDelete = [];
  73451. var i;
  73452. for (i = 0; i < cams.length; i++) {
  73453. var camera = cams[i];
  73454. var cameraName = camera.name;
  73455. if (this._cameras.indexOf(camera) === -1) {
  73456. this._cameras[cameraName] = camera;
  73457. }
  73458. else if (unique) {
  73459. indicesToDelete.push(i);
  73460. }
  73461. }
  73462. for (i = 0; i < indicesToDelete.length; i++) {
  73463. cameras.splice(indicesToDelete[i], 1);
  73464. }
  73465. for (var renderEffectName in this._renderEffects) {
  73466. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73467. this._renderEffects[renderEffectName]._attachCameras(cams);
  73468. }
  73469. }
  73470. };
  73471. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73472. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73473. if (!cams) {
  73474. return;
  73475. }
  73476. for (var renderEffectName in this._renderEffects) {
  73477. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73478. this._renderEffects[renderEffectName]._detachCameras(cams);
  73479. }
  73480. }
  73481. for (var i = 0; i < cams.length; i++) {
  73482. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73483. }
  73484. };
  73485. PostProcessRenderPipeline.prototype._update = function () {
  73486. for (var renderEffectName in this._renderEffects) {
  73487. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73488. this._renderEffects[renderEffectName]._update();
  73489. }
  73490. }
  73491. for (var i = 0; i < this._cameras.length; i++) {
  73492. var cameraName = this._cameras[i].name;
  73493. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73494. this._renderEffectsForIsolatedPass[cameraName]._update();
  73495. }
  73496. }
  73497. };
  73498. PostProcessRenderPipeline.prototype._reset = function () {
  73499. this._renderEffects = {};
  73500. this._renderEffectsForIsolatedPass = new Array();
  73501. };
  73502. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73503. // 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)
  73504. var effectKeys = Object.keys(this._renderEffects);
  73505. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73506. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73507. if (postProcesses) {
  73508. postProcesses[0].samples = sampleCount;
  73509. return true;
  73510. }
  73511. }
  73512. return false;
  73513. };
  73514. PostProcessRenderPipeline.prototype.dispose = function () {
  73515. // Must be implemented by children
  73516. };
  73517. __decorate([
  73518. BABYLON.serialize()
  73519. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73520. return PostProcessRenderPipeline;
  73521. }());
  73522. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73523. })(BABYLON || (BABYLON = {}));
  73524. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73525. var BABYLON;
  73526. (function (BABYLON) {
  73527. /**
  73528. * This represents a depth renderer in Babylon.
  73529. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73530. */
  73531. var DepthRenderer = /** @class */ (function () {
  73532. /**
  73533. * Instantiates a depth renderer
  73534. * @param scene The scene the renderer belongs to
  73535. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73536. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73537. */
  73538. function DepthRenderer(scene, type, camera) {
  73539. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73540. if (camera === void 0) { camera = null; }
  73541. var _this = this;
  73542. this._scene = scene;
  73543. this._camera = camera;
  73544. var engine = scene.getEngine();
  73545. // Render target
  73546. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73547. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73548. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73549. this._depthMap.refreshRate = 1;
  73550. this._depthMap.renderParticles = false;
  73551. this._depthMap.renderList = null;
  73552. // Camera to get depth map from to support multiple concurrent cameras
  73553. this._depthMap.activeCamera = this._camera;
  73554. this._depthMap.ignoreCameraViewport = true;
  73555. this._depthMap.useCameraPostProcesses = false;
  73556. // set default depth value to 1.0 (far away)
  73557. this._depthMap.onClearObservable.add(function (engine) {
  73558. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73559. });
  73560. // Custom render function
  73561. var renderSubMesh = function (subMesh) {
  73562. var mesh = subMesh.getRenderingMesh();
  73563. var scene = _this._scene;
  73564. var engine = scene.getEngine();
  73565. var material = subMesh.getMaterial();
  73566. if (!material) {
  73567. return;
  73568. }
  73569. // Culling and reverse (right handed system)
  73570. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73571. // Managing instances
  73572. var batch = mesh._getInstancesRenderList(subMesh._id);
  73573. if (batch.mustReturn) {
  73574. return;
  73575. }
  73576. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73577. var camera = _this._camera || scene.activeCamera;
  73578. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73579. engine.enableEffect(_this._effect);
  73580. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73581. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73582. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73583. // Alpha test
  73584. if (material && material.needAlphaTesting()) {
  73585. var alphaTexture = material.getAlphaTestTexture();
  73586. if (alphaTexture) {
  73587. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73588. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73589. }
  73590. }
  73591. // Bones
  73592. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73593. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73594. }
  73595. // Draw
  73596. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73597. }
  73598. };
  73599. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73600. var index;
  73601. if (depthOnlySubMeshes.length) {
  73602. engine.setColorWrite(false);
  73603. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73604. renderSubMesh(depthOnlySubMeshes.data[index]);
  73605. }
  73606. engine.setColorWrite(true);
  73607. }
  73608. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73609. renderSubMesh(opaqueSubMeshes.data[index]);
  73610. }
  73611. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73612. renderSubMesh(alphaTestSubMeshes.data[index]);
  73613. }
  73614. };
  73615. }
  73616. /**
  73617. * Creates the depth rendering effect and checks if the effect is ready.
  73618. * @param subMesh The submesh to be used to render the depth map of
  73619. * @param useInstances If multiple world instances should be used
  73620. * @returns if the depth renderer is ready to render the depth map
  73621. */
  73622. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73623. var material = subMesh.getMaterial();
  73624. if (material.disableDepthWrite) {
  73625. return false;
  73626. }
  73627. var defines = [];
  73628. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73629. var mesh = subMesh.getMesh();
  73630. // Alpha test
  73631. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73632. defines.push("#define ALPHATEST");
  73633. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73634. attribs.push(BABYLON.VertexBuffer.UVKind);
  73635. defines.push("#define UV1");
  73636. }
  73637. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73638. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73639. defines.push("#define UV2");
  73640. }
  73641. }
  73642. // Bones
  73643. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73644. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73645. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73646. if (mesh.numBoneInfluencers > 4) {
  73647. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73648. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73649. }
  73650. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73651. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73652. }
  73653. else {
  73654. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73655. }
  73656. // Instances
  73657. if (useInstances) {
  73658. defines.push("#define INSTANCES");
  73659. attribs.push("world0");
  73660. attribs.push("world1");
  73661. attribs.push("world2");
  73662. attribs.push("world3");
  73663. }
  73664. // Get correct effect
  73665. var join = defines.join("\n");
  73666. if (this._cachedDefines !== join) {
  73667. this._cachedDefines = join;
  73668. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73669. }
  73670. return this._effect.isReady();
  73671. };
  73672. /**
  73673. * Gets the texture which the depth map will be written to.
  73674. * @returns The depth map texture
  73675. */
  73676. DepthRenderer.prototype.getDepthMap = function () {
  73677. return this._depthMap;
  73678. };
  73679. /**
  73680. * Disposes of the depth renderer.
  73681. */
  73682. DepthRenderer.prototype.dispose = function () {
  73683. this._depthMap.dispose();
  73684. };
  73685. return DepthRenderer;
  73686. }());
  73687. BABYLON.DepthRenderer = DepthRenderer;
  73688. })(BABYLON || (BABYLON = {}));
  73689. //# sourceMappingURL=babylon.depthRenderer.js.map
  73690. var BABYLON;
  73691. (function (BABYLON) {
  73692. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73693. __extends(SSAORenderingPipeline, _super);
  73694. /**
  73695. * @constructor
  73696. * @param {string} name - The rendering pipeline name
  73697. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73698. * @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 }
  73699. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73700. */
  73701. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73702. var _this = _super.call(this, scene.getEngine(), name) || this;
  73703. // Members
  73704. /**
  73705. * The PassPostProcess id in the pipeline that contains the original scene color
  73706. */
  73707. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73708. /**
  73709. * The SSAO PostProcess id in the pipeline
  73710. */
  73711. _this.SSAORenderEffect = "SSAORenderEffect";
  73712. /**
  73713. * The horizontal blur PostProcess id in the pipeline
  73714. */
  73715. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73716. /**
  73717. * The vertical blur PostProcess id in the pipeline
  73718. */
  73719. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73720. /**
  73721. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73722. */
  73723. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73724. /**
  73725. * The output strength of the SSAO post-process. Default value is 1.0.
  73726. */
  73727. _this.totalStrength = 1.0;
  73728. /**
  73729. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73730. */
  73731. _this.radius = 0.0001;
  73732. /**
  73733. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73734. * Must not be equal to fallOff and superior to fallOff.
  73735. * Default value is 0.975
  73736. */
  73737. _this.area = 0.0075;
  73738. /**
  73739. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73740. * Must not be equal to area and inferior to area.
  73741. * Default value is 0.0
  73742. */
  73743. _this.fallOff = 0.000001;
  73744. /**
  73745. * The base color of the SSAO post-process
  73746. * The final result is "base + ssao" between [0, 1]
  73747. */
  73748. _this.base = 0.5;
  73749. _this._firstUpdate = true;
  73750. _this._scene = scene;
  73751. // Set up assets
  73752. _this._createRandomTexture();
  73753. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73754. var ssaoRatio = ratio.ssaoRatio || ratio;
  73755. var combineRatio = ratio.combineRatio || ratio;
  73756. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73757. _this._createSSAOPostProcess(ssaoRatio);
  73758. _this._createBlurPostProcess(ssaoRatio);
  73759. _this._createSSAOCombinePostProcess(combineRatio);
  73760. // Set up pipeline
  73761. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73762. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73763. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73764. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73765. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73766. // Finish
  73767. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73768. if (cameras)
  73769. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73770. return _this;
  73771. }
  73772. // Public Methods
  73773. /**
  73774. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73775. */
  73776. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73777. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73778. for (var i = 0; i < this._scene.cameras.length; i++) {
  73779. var camera = this._scene.cameras[i];
  73780. this._originalColorPostProcess.dispose(camera);
  73781. this._ssaoPostProcess.dispose(camera);
  73782. this._blurHPostProcess.dispose(camera);
  73783. this._blurVPostProcess.dispose(camera);
  73784. this._ssaoCombinePostProcess.dispose(camera);
  73785. }
  73786. this._randomTexture.dispose();
  73787. if (disableDepthRender)
  73788. this._scene.disableDepthRenderer();
  73789. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73790. _super.prototype.dispose.call(this);
  73791. };
  73792. // Private Methods
  73793. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73794. var _this = this;
  73795. var size = 16;
  73796. 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);
  73797. 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);
  73798. this._blurHPostProcess.onActivateObservable.add(function () {
  73799. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73800. _this._blurHPostProcess.kernel = size * dw;
  73801. });
  73802. this._blurVPostProcess.onActivateObservable.add(function () {
  73803. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73804. _this._blurVPostProcess.kernel = size * dw;
  73805. });
  73806. };
  73807. SSAORenderingPipeline.prototype._rebuild = function () {
  73808. this._firstUpdate = true;
  73809. _super.prototype._rebuild.call(this);
  73810. };
  73811. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73812. var _this = this;
  73813. var numSamples = 16;
  73814. var sampleSphere = [
  73815. 0.5381, 0.1856, -0.4319,
  73816. 0.1379, 0.2486, 0.4430,
  73817. 0.3371, 0.5679, -0.0057,
  73818. -0.6999, -0.0451, -0.0019,
  73819. 0.0689, -0.1598, -0.8547,
  73820. 0.0560, 0.0069, -0.1843,
  73821. -0.0146, 0.1402, 0.0762,
  73822. 0.0100, -0.1924, -0.0344,
  73823. -0.3577, -0.5301, -0.4358,
  73824. -0.3169, 0.1063, 0.0158,
  73825. 0.0103, -0.5869, 0.0046,
  73826. -0.0897, -0.4940, 0.3287,
  73827. 0.7119, -0.0154, -0.0918,
  73828. -0.0533, 0.0596, -0.5411,
  73829. 0.0352, -0.0631, 0.5460,
  73830. -0.4776, 0.2847, -0.0271
  73831. ];
  73832. var samplesFactor = 1.0 / numSamples;
  73833. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73834. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73835. "area", "fallOff", "base", "range", "viewport"
  73836. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73837. this._ssaoPostProcess.onApply = function (effect) {
  73838. if (_this._firstUpdate) {
  73839. effect.setArray3("sampleSphere", sampleSphere);
  73840. effect.setFloat("samplesFactor", samplesFactor);
  73841. effect.setFloat("randTextureTiles", 4.0);
  73842. }
  73843. effect.setFloat("totalStrength", _this.totalStrength);
  73844. effect.setFloat("radius", _this.radius);
  73845. effect.setFloat("area", _this.area);
  73846. effect.setFloat("fallOff", _this.fallOff);
  73847. effect.setFloat("base", _this.base);
  73848. effect.setTexture("textureSampler", _this._depthTexture);
  73849. effect.setTexture("randomSampler", _this._randomTexture);
  73850. };
  73851. };
  73852. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73853. var _this = this;
  73854. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73855. this._ssaoCombinePostProcess.onApply = function (effect) {
  73856. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73857. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73858. };
  73859. };
  73860. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73861. var size = 512;
  73862. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73863. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73864. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73865. var context = this._randomTexture.getContext();
  73866. var rand = function (min, max) {
  73867. return Math.random() * (max - min) + min;
  73868. };
  73869. var randVector = BABYLON.Vector3.Zero();
  73870. for (var x = 0; x < size; x++) {
  73871. for (var y = 0; y < size; y++) {
  73872. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73873. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73874. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73875. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73876. context.fillRect(x, y, 1, 1);
  73877. }
  73878. }
  73879. this._randomTexture.update(false);
  73880. };
  73881. __decorate([
  73882. BABYLON.serialize()
  73883. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73884. __decorate([
  73885. BABYLON.serialize()
  73886. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73887. __decorate([
  73888. BABYLON.serialize()
  73889. ], SSAORenderingPipeline.prototype, "area", void 0);
  73890. __decorate([
  73891. BABYLON.serialize()
  73892. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73893. __decorate([
  73894. BABYLON.serialize()
  73895. ], SSAORenderingPipeline.prototype, "base", void 0);
  73896. return SSAORenderingPipeline;
  73897. }(BABYLON.PostProcessRenderPipeline));
  73898. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73899. })(BABYLON || (BABYLON = {}));
  73900. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73901. var BABYLON;
  73902. (function (BABYLON) {
  73903. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73904. __extends(SSAO2RenderingPipeline, _super);
  73905. /**
  73906. * @constructor
  73907. * @param {string} name - The rendering pipeline name
  73908. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73909. * @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 }
  73910. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73911. */
  73912. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73913. var _this = _super.call(this, scene.getEngine(), name) || this;
  73914. // Members
  73915. /**
  73916. * The PassPostProcess id in the pipeline that contains the original scene color
  73917. */
  73918. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73919. /**
  73920. * The SSAO PostProcess id in the pipeline
  73921. */
  73922. _this.SSAORenderEffect = "SSAORenderEffect";
  73923. /**
  73924. * The horizontal blur PostProcess id in the pipeline
  73925. */
  73926. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73927. /**
  73928. * The vertical blur PostProcess id in the pipeline
  73929. */
  73930. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73931. /**
  73932. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73933. */
  73934. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73935. /**
  73936. * The output strength of the SSAO post-process. Default value is 1.0.
  73937. */
  73938. _this.totalStrength = 1.0;
  73939. /**
  73940. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73941. */
  73942. _this.maxZ = 100.0;
  73943. /**
  73944. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73945. */
  73946. _this.minZAspect = 0.2;
  73947. /**
  73948. * Number of samples used for the SSAO calculations. Default value is 8
  73949. */
  73950. _this._samples = 8;
  73951. /**
  73952. * Are we using bilateral blur ?
  73953. */
  73954. _this._expensiveBlur = true;
  73955. /**
  73956. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73957. */
  73958. _this.radius = 2.0;
  73959. /**
  73960. * The base color of the SSAO post-process
  73961. * The final result is "base + ssao" between [0, 1]
  73962. */
  73963. _this.base = 0.1;
  73964. _this._firstUpdate = true;
  73965. _this._scene = scene;
  73966. _this._ratio = ratio;
  73967. if (!_this.isSupported) {
  73968. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73969. return _this;
  73970. }
  73971. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73972. var blurRatio = _this._ratio.blurRatio || ratio;
  73973. // Set up assets
  73974. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73975. _this._createRandomTexture();
  73976. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73977. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73978. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73979. _this._createSSAOPostProcess(1.0);
  73980. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73981. _this._createSSAOCombinePostProcess(blurRatio);
  73982. // Set up pipeline
  73983. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73984. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73985. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73986. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73987. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73988. // Finish
  73989. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73990. if (cameras)
  73991. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73992. return _this;
  73993. }
  73994. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73995. get: function () {
  73996. return this._samples;
  73997. },
  73998. set: function (n) {
  73999. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74000. this._samples = n;
  74001. this._sampleSphere = this._generateHemisphere();
  74002. this._firstUpdate = true;
  74003. },
  74004. enumerable: true,
  74005. configurable: true
  74006. });
  74007. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74008. get: function () {
  74009. return this._expensiveBlur;
  74010. },
  74011. set: function (b) {
  74012. 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"]);
  74013. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74014. this._expensiveBlur = b;
  74015. this._firstUpdate = true;
  74016. },
  74017. enumerable: true,
  74018. configurable: true
  74019. });
  74020. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74021. /**
  74022. * Support test.
  74023. */
  74024. get: function () {
  74025. var engine = BABYLON.Engine.LastCreatedEngine;
  74026. if (!engine) {
  74027. return false;
  74028. }
  74029. return engine.getCaps().drawBuffersExtension;
  74030. },
  74031. enumerable: true,
  74032. configurable: true
  74033. });
  74034. // Public Methods
  74035. /**
  74036. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74037. */
  74038. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74039. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74040. for (var i = 0; i < this._scene.cameras.length; i++) {
  74041. var camera = this._scene.cameras[i];
  74042. this._originalColorPostProcess.dispose(camera);
  74043. this._ssaoPostProcess.dispose(camera);
  74044. this._blurHPostProcess.dispose(camera);
  74045. this._blurVPostProcess.dispose(camera);
  74046. this._ssaoCombinePostProcess.dispose(camera);
  74047. }
  74048. this._randomTexture.dispose();
  74049. if (disableGeometryBufferRenderer)
  74050. this._scene.disableGeometryBufferRenderer();
  74051. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74052. _super.prototype.dispose.call(this);
  74053. };
  74054. // Private Methods
  74055. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74056. var _this = this;
  74057. this._samplerOffsets = [];
  74058. var expensive = this.expensiveBlur;
  74059. for (var i = -8; i < 8; i++) {
  74060. this._samplerOffsets.push(i * 2 + 0.5);
  74061. }
  74062. 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");
  74063. this._blurHPostProcess.onApply = function (effect) {
  74064. if (!_this._scene.activeCamera) {
  74065. return;
  74066. }
  74067. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74068. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74069. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74070. effect.setFloat("radius", _this.radius);
  74071. effect.setTexture("depthSampler", _this._depthTexture);
  74072. if (_this._firstUpdate) {
  74073. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74074. }
  74075. };
  74076. 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");
  74077. this._blurVPostProcess.onApply = function (effect) {
  74078. if (!_this._scene.activeCamera) {
  74079. return;
  74080. }
  74081. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74082. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74083. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74084. effect.setFloat("radius", _this.radius);
  74085. effect.setTexture("depthSampler", _this._depthTexture);
  74086. if (_this._firstUpdate) {
  74087. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74088. _this._firstUpdate = false;
  74089. }
  74090. };
  74091. };
  74092. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74093. this._firstUpdate = true;
  74094. _super.prototype._rebuild.call(this);
  74095. };
  74096. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74097. var numSamples = this.samples;
  74098. var result = [];
  74099. var vector, scale;
  74100. var rand = function (min, max) {
  74101. return Math.random() * (max - min) + min;
  74102. };
  74103. var i = 0;
  74104. while (i < numSamples) {
  74105. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74106. vector.normalize();
  74107. scale = i / numSamples;
  74108. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74109. vector.scaleInPlace(scale);
  74110. result.push(vector.x, vector.y, vector.z);
  74111. i++;
  74112. }
  74113. return result;
  74114. };
  74115. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74116. var _this = this;
  74117. var numSamples = this.samples;
  74118. this._sampleSphere = this._generateHemisphere();
  74119. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74120. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74121. "base", "range", "projection", "near", "far", "texelSize",
  74122. "xViewport", "yViewport", "maxZ", "minZAspect"
  74123. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74124. this._ssaoPostProcess.onApply = function (effect) {
  74125. if (_this._firstUpdate) {
  74126. effect.setArray3("sampleSphere", _this._sampleSphere);
  74127. effect.setFloat("randTextureTiles", 4.0);
  74128. }
  74129. if (!_this._scene.activeCamera) {
  74130. return;
  74131. }
  74132. effect.setFloat("samplesFactor", 1 / _this.samples);
  74133. effect.setFloat("totalStrength", _this.totalStrength);
  74134. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74135. effect.setFloat("radius", _this.radius);
  74136. effect.setFloat("maxZ", _this.maxZ);
  74137. effect.setFloat("minZAspect", _this.minZAspect);
  74138. effect.setFloat("base", _this.base);
  74139. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74140. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74141. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74142. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74143. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74144. effect.setTexture("textureSampler", _this._depthTexture);
  74145. effect.setTexture("normalSampler", _this._normalTexture);
  74146. effect.setTexture("randomSampler", _this._randomTexture);
  74147. };
  74148. };
  74149. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74150. var _this = this;
  74151. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74152. this._ssaoCombinePostProcess.onApply = function (effect) {
  74153. var viewport = _this._scene.activeCamera.viewport;
  74154. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74155. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74156. };
  74157. };
  74158. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74159. var size = 512;
  74160. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74161. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74162. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74163. var context = this._randomTexture.getContext();
  74164. var rand = function (min, max) {
  74165. return Math.random() * (max - min) + min;
  74166. };
  74167. var randVector = BABYLON.Vector3.Zero();
  74168. for (var x = 0; x < size; x++) {
  74169. for (var y = 0; y < size; y++) {
  74170. randVector.x = rand(0.0, 1.0);
  74171. randVector.y = rand(0.0, 1.0);
  74172. randVector.z = 0.0;
  74173. randVector.normalize();
  74174. randVector.scaleInPlace(255);
  74175. randVector.x = Math.floor(randVector.x);
  74176. randVector.y = Math.floor(randVector.y);
  74177. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74178. context.fillRect(x, y, 1, 1);
  74179. }
  74180. }
  74181. this._randomTexture.update(false);
  74182. };
  74183. /**
  74184. * Serialize the rendering pipeline (Used when exporting)
  74185. * @returns the serialized object
  74186. */
  74187. SSAO2RenderingPipeline.prototype.serialize = function () {
  74188. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74189. serializationObject.customType = "SSAO2RenderingPipeline";
  74190. return serializationObject;
  74191. };
  74192. /**
  74193. * Parse the serialized pipeline
  74194. * @param source Source pipeline.
  74195. * @param scene The scene to load the pipeline to.
  74196. * @param rootUrl The URL of the serialized pipeline.
  74197. * @returns An instantiated pipeline from the serialized object.
  74198. */
  74199. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74200. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74201. };
  74202. __decorate([
  74203. BABYLON.serialize()
  74204. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74205. __decorate([
  74206. BABYLON.serialize()
  74207. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74208. __decorate([
  74209. BABYLON.serialize()
  74210. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74211. __decorate([
  74212. BABYLON.serialize("samples")
  74213. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74214. __decorate([
  74215. BABYLON.serialize()
  74216. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74217. __decorate([
  74218. BABYLON.serialize("expensiveBlur")
  74219. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74220. __decorate([
  74221. BABYLON.serialize()
  74222. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74223. __decorate([
  74224. BABYLON.serialize()
  74225. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74226. return SSAO2RenderingPipeline;
  74227. }(BABYLON.PostProcessRenderPipeline));
  74228. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74229. })(BABYLON || (BABYLON = {}));
  74230. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74231. // BABYLON.JS Chromatic Aberration GLSL Shader
  74232. // Author: Olivier Guyot
  74233. // Separates very slightly R, G and B colors on the edges of the screen
  74234. // Inspired by Francois Tarlier & Martins Upitis
  74235. var BABYLON;
  74236. (function (BABYLON) {
  74237. var LensRenderingPipeline = /** @class */ (function (_super) {
  74238. __extends(LensRenderingPipeline, _super);
  74239. /**
  74240. * @constructor
  74241. *
  74242. * Effect parameters are as follow:
  74243. * {
  74244. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74245. * edge_blur: number; // from 0 to x (1 for realism)
  74246. * distortion: number; // from 0 to x (1 for realism)
  74247. * grain_amount: number; // from 0 to 1
  74248. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74249. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74250. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74251. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74252. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74253. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74254. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74255. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74256. * }
  74257. * Note: if an effect parameter is unset, effect is disabled
  74258. *
  74259. * @param {string} name - The rendering pipeline name
  74260. * @param {object} parameters - An object containing all parameters (see above)
  74261. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74262. * @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)
  74263. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74264. */
  74265. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74266. if (ratio === void 0) { ratio = 1.0; }
  74267. var _this = _super.call(this, scene.getEngine(), name) || this;
  74268. // Lens effects can be of the following:
  74269. // - chromatic aberration (slight shift of RGB colors)
  74270. // - blur on the edge of the lens
  74271. // - lens distortion
  74272. // - depth-of-field blur & highlights enhancing
  74273. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74274. // - grain effect (noise or custom texture)
  74275. // Two additional texture samplers are needed:
  74276. // - depth map (for depth-of-field)
  74277. // - grain texture
  74278. /**
  74279. * The chromatic aberration PostProcess id in the pipeline
  74280. */
  74281. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74282. /**
  74283. * The highlights enhancing PostProcess id in the pipeline
  74284. */
  74285. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74286. /**
  74287. * The depth-of-field PostProcess id in the pipeline
  74288. */
  74289. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74290. _this._scene = scene;
  74291. // Fetch texture samplers
  74292. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74293. if (parameters.grain_texture) {
  74294. _this._grainTexture = parameters.grain_texture;
  74295. }
  74296. else {
  74297. _this._createGrainTexture();
  74298. }
  74299. // save parameters
  74300. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74301. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74302. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74303. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74304. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74305. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74306. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74307. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74308. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74309. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74310. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74311. // Create effects
  74312. _this._createChromaticAberrationPostProcess(ratio);
  74313. _this._createHighlightsPostProcess(ratio);
  74314. _this._createDepthOfFieldPostProcess(ratio / 4);
  74315. // Set up pipeline
  74316. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74317. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74318. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74319. if (_this._highlightsGain === -1) {
  74320. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74321. }
  74322. // Finish
  74323. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74324. if (cameras) {
  74325. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74326. }
  74327. return _this;
  74328. }
  74329. // public methods (self explanatory)
  74330. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74331. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74332. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74333. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74334. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74335. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74336. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74337. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74338. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74339. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74340. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74341. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74342. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74343. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74344. };
  74345. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74346. this._highlightsPostProcess.updateEffect();
  74347. };
  74348. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74349. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74350. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74351. this._highlightsGain = amount;
  74352. };
  74353. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74354. if (this._highlightsGain === -1) {
  74355. this._highlightsGain = 1.0;
  74356. }
  74357. this._highlightsThreshold = amount;
  74358. };
  74359. LensRenderingPipeline.prototype.disableHighlights = function () {
  74360. this._highlightsGain = -1;
  74361. };
  74362. /**
  74363. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74364. */
  74365. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74366. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74367. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74368. this._chromaticAberrationPostProcess = null;
  74369. this._highlightsPostProcess = null;
  74370. this._depthOfFieldPostProcess = null;
  74371. this._grainTexture.dispose();
  74372. if (disableDepthRender)
  74373. this._scene.disableDepthRenderer();
  74374. };
  74375. // colors shifting and distortion
  74376. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74377. var _this = this;
  74378. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74379. [], // samplers
  74380. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74381. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74382. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74383. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74384. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74385. effect.setFloat('radialIntensity', 1);
  74386. effect.setFloat2('direction', 17, 17);
  74387. effect.setFloat2('centerPosition', 0.5, 0.5);
  74388. };
  74389. };
  74390. // highlights enhancing
  74391. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74392. var _this = this;
  74393. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74394. [], // samplers
  74395. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74396. this._highlightsPostProcess.onApply = function (effect) {
  74397. effect.setFloat('gain', _this._highlightsGain);
  74398. effect.setFloat('threshold', _this._highlightsThreshold);
  74399. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74400. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74401. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74402. };
  74403. };
  74404. // colors shifting and distortion
  74405. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74406. var _this = this;
  74407. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74408. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74409. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74410. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74411. this._depthOfFieldPostProcess.onApply = function (effect) {
  74412. effect.setTexture("depthSampler", _this._depthTexture);
  74413. effect.setTexture("grainSampler", _this._grainTexture);
  74414. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74415. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74416. effect.setFloat('grain_amount', _this._grainAmount);
  74417. effect.setBool('blur_noise', _this._blurNoise);
  74418. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74419. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74420. effect.setFloat('distortion', _this._distortion);
  74421. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74422. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74423. effect.setFloat('aperture', _this._dofAperture);
  74424. effect.setFloat('darken', _this._dofDarken);
  74425. effect.setFloat('edge_blur', _this._edgeBlur);
  74426. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74427. if (_this._scene.activeCamera) {
  74428. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74429. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74430. }
  74431. };
  74432. };
  74433. // creates a black and white random noise texture, 512x512
  74434. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74435. var size = 512;
  74436. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74437. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74438. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74439. var context = this._grainTexture.getContext();
  74440. var rand = function (min, max) {
  74441. return Math.random() * (max - min) + min;
  74442. };
  74443. var value;
  74444. for (var x = 0; x < size; x++) {
  74445. for (var y = 0; y < size; y++) {
  74446. value = Math.floor(rand(0.42, 0.58) * 255);
  74447. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74448. context.fillRect(x, y, 1, 1);
  74449. }
  74450. }
  74451. this._grainTexture.update(false);
  74452. };
  74453. return LensRenderingPipeline;
  74454. }(BABYLON.PostProcessRenderPipeline));
  74455. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74456. })(BABYLON || (BABYLON = {}));
  74457. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74458. var BABYLON;
  74459. (function (BABYLON) {
  74460. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74461. __extends(StandardRenderingPipeline, _super);
  74462. /**
  74463. * @constructor
  74464. * @param {string} name - The rendering pipeline name
  74465. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74466. * @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)
  74467. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74468. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74469. */
  74470. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74471. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74472. var _this = _super.call(this, scene.getEngine(), name) || this;
  74473. _this.downSampleX4PostProcess = null;
  74474. _this.brightPassPostProcess = null;
  74475. _this.blurHPostProcesses = [];
  74476. _this.blurVPostProcesses = [];
  74477. _this.textureAdderPostProcess = null;
  74478. _this.volumetricLightPostProcess = null;
  74479. _this.volumetricLightSmoothXPostProcess = null;
  74480. _this.volumetricLightSmoothYPostProcess = null;
  74481. _this.volumetricLightMergePostProces = null;
  74482. _this.volumetricLightFinalPostProcess = null;
  74483. _this.luminancePostProcess = null;
  74484. _this.luminanceDownSamplePostProcesses = [];
  74485. _this.hdrPostProcess = null;
  74486. _this.textureAdderFinalPostProcess = null;
  74487. _this.lensFlareFinalPostProcess = null;
  74488. _this.hdrFinalPostProcess = null;
  74489. _this.lensFlarePostProcess = null;
  74490. _this.lensFlareComposePostProcess = null;
  74491. _this.motionBlurPostProcess = null;
  74492. _this.depthOfFieldPostProcess = null;
  74493. // Values
  74494. _this.brightThreshold = 1.0;
  74495. _this.blurWidth = 512.0;
  74496. _this.horizontalBlur = false;
  74497. _this.exposure = 1.0;
  74498. _this.lensTexture = null;
  74499. _this.volumetricLightCoefficient = 0.2;
  74500. _this.volumetricLightPower = 4.0;
  74501. _this.volumetricLightBlurScale = 64.0;
  74502. _this.sourceLight = null;
  74503. _this.hdrMinimumLuminance = 1.0;
  74504. _this.hdrDecreaseRate = 0.5;
  74505. _this.hdrIncreaseRate = 0.5;
  74506. _this.lensColorTexture = null;
  74507. _this.lensFlareStrength = 20.0;
  74508. _this.lensFlareGhostDispersal = 1.4;
  74509. _this.lensFlareHaloWidth = 0.7;
  74510. _this.lensFlareDistortionStrength = 16.0;
  74511. _this.lensStarTexture = null;
  74512. _this.lensFlareDirtTexture = null;
  74513. _this.depthOfFieldDistance = 10.0;
  74514. _this.depthOfFieldBlurWidth = 64.0;
  74515. _this.motionStrength = 1.0;
  74516. // IAnimatable
  74517. _this.animations = [];
  74518. _this._currentDepthOfFieldSource = null;
  74519. _this._hdrCurrentLuminance = 1.0;
  74520. // Getters and setters
  74521. _this._bloomEnabled = true;
  74522. _this._depthOfFieldEnabled = false;
  74523. _this._vlsEnabled = false;
  74524. _this._lensFlareEnabled = false;
  74525. _this._hdrEnabled = false;
  74526. _this._motionBlurEnabled = false;
  74527. _this._motionBlurSamples = 64.0;
  74528. _this._volumetricLightStepsCount = 50.0;
  74529. _this._cameras = cameras || [];
  74530. // Initialize
  74531. _this._scene = scene;
  74532. _this._basePostProcess = originalPostProcess;
  74533. _this._ratio = ratio;
  74534. // Misc
  74535. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74536. // Finish
  74537. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74538. _this._buildPipeline();
  74539. return _this;
  74540. }
  74541. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74542. get: function () {
  74543. return this._bloomEnabled;
  74544. },
  74545. set: function (enabled) {
  74546. if (this._bloomEnabled === enabled) {
  74547. return;
  74548. }
  74549. this._bloomEnabled = enabled;
  74550. this._buildPipeline();
  74551. },
  74552. enumerable: true,
  74553. configurable: true
  74554. });
  74555. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74556. get: function () {
  74557. return this._depthOfFieldEnabled;
  74558. },
  74559. set: function (enabled) {
  74560. if (this._depthOfFieldEnabled === enabled) {
  74561. return;
  74562. }
  74563. this._depthOfFieldEnabled = enabled;
  74564. this._buildPipeline();
  74565. },
  74566. enumerable: true,
  74567. configurable: true
  74568. });
  74569. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74570. get: function () {
  74571. return this._lensFlareEnabled;
  74572. },
  74573. set: function (enabled) {
  74574. if (this._lensFlareEnabled === enabled) {
  74575. return;
  74576. }
  74577. this._lensFlareEnabled = enabled;
  74578. this._buildPipeline();
  74579. },
  74580. enumerable: true,
  74581. configurable: true
  74582. });
  74583. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74584. get: function () {
  74585. return this._hdrEnabled;
  74586. },
  74587. set: function (enabled) {
  74588. if (this._hdrEnabled === enabled) {
  74589. return;
  74590. }
  74591. this._hdrEnabled = enabled;
  74592. this._buildPipeline();
  74593. },
  74594. enumerable: true,
  74595. configurable: true
  74596. });
  74597. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74598. get: function () {
  74599. return this._vlsEnabled;
  74600. },
  74601. set: function (enabled) {
  74602. if (this._vlsEnabled === enabled) {
  74603. return;
  74604. }
  74605. if (enabled) {
  74606. var geometry = this._scene.enableGeometryBufferRenderer();
  74607. if (!geometry) {
  74608. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74609. return;
  74610. }
  74611. }
  74612. this._vlsEnabled = enabled;
  74613. this._buildPipeline();
  74614. },
  74615. enumerable: true,
  74616. configurable: true
  74617. });
  74618. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74619. get: function () {
  74620. return this._motionBlurEnabled;
  74621. },
  74622. set: function (enabled) {
  74623. if (this._motionBlurEnabled === enabled) {
  74624. return;
  74625. }
  74626. this._motionBlurEnabled = enabled;
  74627. this._buildPipeline();
  74628. },
  74629. enumerable: true,
  74630. configurable: true
  74631. });
  74632. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74633. get: function () {
  74634. return this._volumetricLightStepsCount;
  74635. },
  74636. set: function (count) {
  74637. if (this.volumetricLightPostProcess) {
  74638. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74639. }
  74640. this._volumetricLightStepsCount = count;
  74641. },
  74642. enumerable: true,
  74643. configurable: true
  74644. });
  74645. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74646. get: function () {
  74647. return this._motionBlurSamples;
  74648. },
  74649. set: function (samples) {
  74650. if (this.motionBlurPostProcess) {
  74651. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74652. }
  74653. this._motionBlurSamples = samples;
  74654. },
  74655. enumerable: true,
  74656. configurable: true
  74657. });
  74658. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74659. var _this = this;
  74660. var ratio = this._ratio;
  74661. var scene = this._scene;
  74662. this._disposePostProcesses();
  74663. this._reset();
  74664. // Create pass post-process
  74665. if (!this._basePostProcess) {
  74666. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74667. this.originalPostProcess.onApply = function (effect) {
  74668. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74669. };
  74670. }
  74671. else {
  74672. this.originalPostProcess = this._basePostProcess;
  74673. }
  74674. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74675. this._currentDepthOfFieldSource = this.originalPostProcess;
  74676. if (this._bloomEnabled) {
  74677. // Create down sample X4 post-process
  74678. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74679. // Create bright pass post-process
  74680. this._createBrightPassPostProcess(scene, ratio / 2);
  74681. // Create gaussian blur post-processes (down sampling blurs)
  74682. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74683. // Create texture adder post-process
  74684. this._createTextureAdderPostProcess(scene, ratio);
  74685. // Create depth-of-field source post-process
  74686. 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);
  74687. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74688. }
  74689. if (this._vlsEnabled) {
  74690. // Create volumetric light
  74691. this._createVolumetricLightPostProcess(scene, ratio);
  74692. // Create volumetric light final post-process
  74693. 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);
  74694. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74695. }
  74696. if (this._lensFlareEnabled) {
  74697. // Create lens flare post-process
  74698. this._createLensFlarePostProcess(scene, ratio);
  74699. // Create depth-of-field source post-process post lens-flare and disable it now
  74700. 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);
  74701. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74702. }
  74703. if (this._hdrEnabled) {
  74704. // Create luminance
  74705. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74706. // Create HDR
  74707. this._createHdrPostProcess(scene, ratio);
  74708. // Create depth-of-field source post-process post hdr and disable it now
  74709. 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);
  74710. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74711. }
  74712. if (this._depthOfFieldEnabled) {
  74713. // Create gaussian blur used by depth-of-field
  74714. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74715. // Create depth-of-field post-process
  74716. this._createDepthOfFieldPostProcess(scene, ratio);
  74717. }
  74718. if (this._motionBlurEnabled) {
  74719. // Create motion blur post-process
  74720. this._createMotionBlurPostProcess(scene, ratio);
  74721. }
  74722. if (this._cameras !== null) {
  74723. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74724. }
  74725. };
  74726. // Down Sample X4 Post-Processs
  74727. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74728. var _this = this;
  74729. var downSampleX4Offsets = new Array(32);
  74730. 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);
  74731. this.downSampleX4PostProcess.onApply = function (effect) {
  74732. var id = 0;
  74733. var width = _this.downSampleX4PostProcess.width;
  74734. var height = _this.downSampleX4PostProcess.height;
  74735. for (var i = -2; i < 2; i++) {
  74736. for (var j = -2; j < 2; j++) {
  74737. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74738. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74739. id += 2;
  74740. }
  74741. }
  74742. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74743. };
  74744. // Add to pipeline
  74745. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74746. };
  74747. // Brightpass Post-Process
  74748. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74749. var _this = this;
  74750. var brightOffsets = new Array(8);
  74751. 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);
  74752. this.brightPassPostProcess.onApply = function (effect) {
  74753. var sU = (1.0 / _this.brightPassPostProcess.width);
  74754. var sV = (1.0 / _this.brightPassPostProcess.height);
  74755. brightOffsets[0] = -0.5 * sU;
  74756. brightOffsets[1] = 0.5 * sV;
  74757. brightOffsets[2] = 0.5 * sU;
  74758. brightOffsets[3] = 0.5 * sV;
  74759. brightOffsets[4] = -0.5 * sU;
  74760. brightOffsets[5] = -0.5 * sV;
  74761. brightOffsets[6] = 0.5 * sU;
  74762. brightOffsets[7] = -0.5 * sV;
  74763. effect.setArray2("dsOffsets", brightOffsets);
  74764. effect.setFloat("brightThreshold", _this.brightThreshold);
  74765. };
  74766. // Add to pipeline
  74767. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74768. };
  74769. // Create blur H&V post-processes
  74770. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74771. var _this = this;
  74772. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74773. var engine = scene.getEngine();
  74774. 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);
  74775. 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);
  74776. blurX.onActivateObservable.add(function () {
  74777. var dw = blurX.width / engine.getRenderWidth();
  74778. blurX.kernel = _this[blurWidthKey] * dw;
  74779. });
  74780. blurY.onActivateObservable.add(function () {
  74781. var dw = blurY.height / engine.getRenderHeight();
  74782. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74783. });
  74784. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74785. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74786. this.blurHPostProcesses.push(blurX);
  74787. this.blurVPostProcesses.push(blurY);
  74788. };
  74789. // Create texture adder post-process
  74790. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74791. var _this = this;
  74792. 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);
  74793. this.textureAdderPostProcess.onApply = function (effect) {
  74794. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74795. effect.setTexture("lensSampler", _this.lensTexture);
  74796. effect.setFloat("exposure", _this.exposure);
  74797. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74798. };
  74799. // Add to pipeline
  74800. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74801. };
  74802. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74803. var _this = this;
  74804. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74805. geometryRenderer.enablePosition = true;
  74806. var geometry = geometryRenderer.getGBuffer();
  74807. // Base post-process
  74808. 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));
  74809. var depthValues = BABYLON.Vector2.Zero();
  74810. this.volumetricLightPostProcess.onApply = function (effect) {
  74811. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74812. var generator = _this.sourceLight.getShadowGenerator();
  74813. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74814. effect.setTexture("positionSampler", geometry.textures[2]);
  74815. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74816. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74817. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74818. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74819. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74820. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74821. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74822. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74823. effect.setVector2("depthValues", depthValues);
  74824. }
  74825. };
  74826. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74827. // Smooth
  74828. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74829. // Merge
  74830. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74831. this.volumetricLightMergePostProces.onApply = function (effect) {
  74832. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74833. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74834. };
  74835. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74836. };
  74837. // Create luminance
  74838. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74839. var _this = this;
  74840. // Create luminance
  74841. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74842. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74843. var offsets = [];
  74844. this.luminancePostProcess.onApply = function (effect) {
  74845. var sU = (1.0 / _this.luminancePostProcess.width);
  74846. var sV = (1.0 / _this.luminancePostProcess.height);
  74847. offsets[0] = -0.5 * sU;
  74848. offsets[1] = 0.5 * sV;
  74849. offsets[2] = 0.5 * sU;
  74850. offsets[3] = 0.5 * sV;
  74851. offsets[4] = -0.5 * sU;
  74852. offsets[5] = -0.5 * sV;
  74853. offsets[6] = 0.5 * sU;
  74854. offsets[7] = -0.5 * sV;
  74855. effect.setArray2("lumOffsets", offsets);
  74856. };
  74857. // Add to pipeline
  74858. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74859. // Create down sample luminance
  74860. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74861. var size = Math.pow(3, i);
  74862. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74863. if (i === 0) {
  74864. defines += "#define FINAL_DOWN_SAMPLER";
  74865. }
  74866. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74867. this.luminanceDownSamplePostProcesses.push(postProcess);
  74868. }
  74869. // Create callbacks and add effects
  74870. var lastLuminance = this.luminancePostProcess;
  74871. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74872. var downSampleOffsets = new Array(18);
  74873. pp.onApply = function (effect) {
  74874. if (!lastLuminance) {
  74875. return;
  74876. }
  74877. var id = 0;
  74878. for (var x = -1; x < 2; x++) {
  74879. for (var y = -1; y < 2; y++) {
  74880. downSampleOffsets[id] = x / lastLuminance.width;
  74881. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74882. id += 2;
  74883. }
  74884. }
  74885. effect.setArray2("dsOffsets", downSampleOffsets);
  74886. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74887. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74888. lastLuminance = _this.luminancePostProcess;
  74889. }
  74890. else {
  74891. lastLuminance = pp;
  74892. }
  74893. };
  74894. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74895. pp.onAfterRender = function (effect) {
  74896. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74897. 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);
  74898. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74899. };
  74900. }
  74901. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74902. });
  74903. };
  74904. // Create HDR post-process
  74905. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74906. var _this = this;
  74907. 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);
  74908. var outputLiminance = 1;
  74909. var time = 0;
  74910. var lastTime = 0;
  74911. this.hdrPostProcess.onApply = function (effect) {
  74912. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74913. time += scene.getEngine().getDeltaTime();
  74914. if (outputLiminance < 0) {
  74915. outputLiminance = _this._hdrCurrentLuminance;
  74916. }
  74917. else {
  74918. var dt = (lastTime - time) / 1000.0;
  74919. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74920. outputLiminance += _this.hdrDecreaseRate * dt;
  74921. }
  74922. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74923. outputLiminance -= _this.hdrIncreaseRate * dt;
  74924. }
  74925. else {
  74926. outputLiminance = _this._hdrCurrentLuminance;
  74927. }
  74928. }
  74929. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74930. effect.setFloat("averageLuminance", outputLiminance);
  74931. lastTime = time;
  74932. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74933. };
  74934. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74935. };
  74936. // Create lens flare post-process
  74937. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74938. var _this = this;
  74939. 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);
  74940. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74941. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74942. 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);
  74943. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74944. var resolution = new BABYLON.Vector2(0, 0);
  74945. // Lens flare
  74946. this.lensFlarePostProcess.onApply = function (effect) {
  74947. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74948. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74949. effect.setFloat("strength", _this.lensFlareStrength);
  74950. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74951. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74952. // Shift
  74953. resolution.x = _this.lensFlarePostProcess.width;
  74954. resolution.y = _this.lensFlarePostProcess.height;
  74955. effect.setVector2("resolution", resolution);
  74956. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74957. };
  74958. // Compose
  74959. 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);
  74960. 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);
  74961. this.lensFlareComposePostProcess.onApply = function (effect) {
  74962. if (!_this._scene.activeCamera) {
  74963. return;
  74964. }
  74965. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74966. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74967. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74968. // Lens start rotation matrix
  74969. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74970. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74971. 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));
  74972. camRot *= 4.0;
  74973. 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);
  74974. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74975. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74976. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74977. };
  74978. };
  74979. // Create depth-of-field post-process
  74980. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74981. var _this = this;
  74982. 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);
  74983. this.depthOfFieldPostProcess.onApply = function (effect) {
  74984. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74985. effect.setTexture("depthSampler", _this._getDepthTexture());
  74986. effect.setFloat("distance", _this.depthOfFieldDistance);
  74987. };
  74988. // Add to pipeline
  74989. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74990. };
  74991. // Create motion blur post-process
  74992. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74993. var _this = this;
  74994. 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);
  74995. var motionScale = 0;
  74996. var prevViewProjection = BABYLON.Matrix.Identity();
  74997. var invViewProjection = BABYLON.Matrix.Identity();
  74998. var viewProjection = BABYLON.Matrix.Identity();
  74999. var screenSize = BABYLON.Vector2.Zero();
  75000. this.motionBlurPostProcess.onApply = function (effect) {
  75001. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75002. viewProjection.invertToRef(invViewProjection);
  75003. effect.setMatrix("inverseViewProjection", invViewProjection);
  75004. effect.setMatrix("prevViewProjection", prevViewProjection);
  75005. prevViewProjection = viewProjection;
  75006. screenSize.x = _this.motionBlurPostProcess.width;
  75007. screenSize.y = _this.motionBlurPostProcess.height;
  75008. effect.setVector2("screenSize", screenSize);
  75009. motionScale = scene.getEngine().getFps() / 60.0;
  75010. effect.setFloat("motionScale", motionScale);
  75011. effect.setFloat("motionStrength", _this.motionStrength);
  75012. effect.setTexture("depthSampler", _this._getDepthTexture());
  75013. };
  75014. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75015. };
  75016. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75017. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75018. var renderer = this._scene.enableGeometryBufferRenderer();
  75019. return renderer.getGBuffer().textures[0];
  75020. }
  75021. return this._scene.enableDepthRenderer().getDepthMap();
  75022. };
  75023. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75024. for (var i = 0; i < this._cameras.length; i++) {
  75025. var camera = this._cameras[i];
  75026. if (this.originalPostProcess) {
  75027. this.originalPostProcess.dispose(camera);
  75028. }
  75029. if (this.downSampleX4PostProcess) {
  75030. this.downSampleX4PostProcess.dispose(camera);
  75031. }
  75032. if (this.brightPassPostProcess) {
  75033. this.brightPassPostProcess.dispose(camera);
  75034. }
  75035. if (this.textureAdderPostProcess) {
  75036. this.textureAdderPostProcess.dispose(camera);
  75037. }
  75038. if (this.textureAdderFinalPostProcess) {
  75039. this.textureAdderFinalPostProcess.dispose(camera);
  75040. }
  75041. if (this.volumetricLightPostProcess) {
  75042. this.volumetricLightPostProcess.dispose(camera);
  75043. }
  75044. if (this.volumetricLightSmoothXPostProcess) {
  75045. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75046. }
  75047. if (this.volumetricLightSmoothYPostProcess) {
  75048. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75049. }
  75050. if (this.volumetricLightMergePostProces) {
  75051. this.volumetricLightMergePostProces.dispose(camera);
  75052. }
  75053. if (this.volumetricLightFinalPostProcess) {
  75054. this.volumetricLightFinalPostProcess.dispose(camera);
  75055. }
  75056. if (this.lensFlarePostProcess) {
  75057. this.lensFlarePostProcess.dispose(camera);
  75058. }
  75059. if (this.lensFlareComposePostProcess) {
  75060. this.lensFlareComposePostProcess.dispose(camera);
  75061. }
  75062. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75063. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75064. }
  75065. if (this.luminancePostProcess) {
  75066. this.luminancePostProcess.dispose(camera);
  75067. }
  75068. if (this.hdrPostProcess) {
  75069. this.hdrPostProcess.dispose(camera);
  75070. }
  75071. if (this.hdrFinalPostProcess) {
  75072. this.hdrFinalPostProcess.dispose(camera);
  75073. }
  75074. if (this.depthOfFieldPostProcess) {
  75075. this.depthOfFieldPostProcess.dispose(camera);
  75076. }
  75077. if (this.motionBlurPostProcess) {
  75078. this.motionBlurPostProcess.dispose(camera);
  75079. }
  75080. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75081. this.blurHPostProcesses[j].dispose(camera);
  75082. }
  75083. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75084. this.blurVPostProcesses[j].dispose(camera);
  75085. }
  75086. }
  75087. this.originalPostProcess = null;
  75088. this.downSampleX4PostProcess = null;
  75089. this.brightPassPostProcess = null;
  75090. this.textureAdderPostProcess = null;
  75091. this.textureAdderFinalPostProcess = null;
  75092. this.volumetricLightPostProcess = null;
  75093. this.volumetricLightSmoothXPostProcess = null;
  75094. this.volumetricLightSmoothYPostProcess = null;
  75095. this.volumetricLightMergePostProces = null;
  75096. this.volumetricLightFinalPostProcess = null;
  75097. this.lensFlarePostProcess = null;
  75098. this.lensFlareComposePostProcess = null;
  75099. this.luminancePostProcess = null;
  75100. this.hdrPostProcess = null;
  75101. this.hdrFinalPostProcess = null;
  75102. this.depthOfFieldPostProcess = null;
  75103. this.motionBlurPostProcess = null;
  75104. this.luminanceDownSamplePostProcesses = [];
  75105. this.blurHPostProcesses = [];
  75106. this.blurVPostProcesses = [];
  75107. };
  75108. /**
  75109. * Dispose of the pipeline and stop all post processes
  75110. */
  75111. StandardRenderingPipeline.prototype.dispose = function () {
  75112. this._disposePostProcesses();
  75113. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75114. _super.prototype.dispose.call(this);
  75115. };
  75116. /**
  75117. * Serialize the rendering pipeline (Used when exporting)
  75118. * @returns the serialized object
  75119. */
  75120. StandardRenderingPipeline.prototype.serialize = function () {
  75121. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75122. if (this.sourceLight) {
  75123. serializationObject.sourceLightId = this.sourceLight.id;
  75124. }
  75125. serializationObject.customType = "StandardRenderingPipeline";
  75126. return serializationObject;
  75127. };
  75128. /**
  75129. * Parse the serialized pipeline
  75130. * @param source Source pipeline.
  75131. * @param scene The scene to load the pipeline to.
  75132. * @param rootUrl The URL of the serialized pipeline.
  75133. * @returns An instantiated pipeline from the serialized object.
  75134. */
  75135. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75136. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75137. if (source.sourceLightId) {
  75138. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75139. }
  75140. return p;
  75141. };
  75142. // Luminance steps
  75143. StandardRenderingPipeline.LuminanceSteps = 6;
  75144. __decorate([
  75145. BABYLON.serialize()
  75146. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75147. __decorate([
  75148. BABYLON.serialize()
  75149. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75150. __decorate([
  75151. BABYLON.serialize()
  75152. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75153. __decorate([
  75154. BABYLON.serialize()
  75155. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75156. __decorate([
  75157. BABYLON.serializeAsTexture("lensTexture")
  75158. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75159. __decorate([
  75160. BABYLON.serialize()
  75161. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75162. __decorate([
  75163. BABYLON.serialize()
  75164. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75165. __decorate([
  75166. BABYLON.serialize()
  75167. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75168. __decorate([
  75169. BABYLON.serialize()
  75170. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75171. __decorate([
  75172. BABYLON.serialize()
  75173. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75174. __decorate([
  75175. BABYLON.serialize()
  75176. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75177. __decorate([
  75178. BABYLON.serializeAsTexture("lensColorTexture")
  75179. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75180. __decorate([
  75181. BABYLON.serialize()
  75182. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75183. __decorate([
  75184. BABYLON.serialize()
  75185. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75186. __decorate([
  75187. BABYLON.serialize()
  75188. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75189. __decorate([
  75190. BABYLON.serialize()
  75191. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75192. __decorate([
  75193. BABYLON.serializeAsTexture("lensStarTexture")
  75194. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75195. __decorate([
  75196. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75197. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75198. __decorate([
  75199. BABYLON.serialize()
  75200. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75201. __decorate([
  75202. BABYLON.serialize()
  75203. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75204. __decorate([
  75205. BABYLON.serialize()
  75206. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75207. __decorate([
  75208. BABYLON.serialize()
  75209. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75210. __decorate([
  75211. BABYLON.serialize()
  75212. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75213. __decorate([
  75214. BABYLON.serialize()
  75215. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75216. __decorate([
  75217. BABYLON.serialize()
  75218. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75219. __decorate([
  75220. BABYLON.serialize()
  75221. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75222. __decorate([
  75223. BABYLON.serialize()
  75224. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75225. __decorate([
  75226. BABYLON.serialize()
  75227. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75228. __decorate([
  75229. BABYLON.serialize()
  75230. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75231. __decorate([
  75232. BABYLON.serialize()
  75233. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75234. return StandardRenderingPipeline;
  75235. }(BABYLON.PostProcessRenderPipeline));
  75236. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75237. })(BABYLON || (BABYLON = {}));
  75238. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75239. var BABYLON;
  75240. (function (BABYLON) {
  75241. var FxaaPostProcess = /** @class */ (function (_super) {
  75242. __extends(FxaaPostProcess, _super);
  75243. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75244. if (camera === void 0) { camera = null; }
  75245. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75246. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75247. var defines = _this._getDefines();
  75248. _this.updateEffect(defines);
  75249. _this.onApplyObservable.add(function (effect) {
  75250. var texelSize = _this.texelSize;
  75251. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75252. });
  75253. return _this;
  75254. }
  75255. FxaaPostProcess.prototype._getDefines = function () {
  75256. var engine = this.getEngine();
  75257. if (!engine) {
  75258. return null;
  75259. }
  75260. var glInfo = engine.getGlInfo();
  75261. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75262. return "#define MALI 1\n";
  75263. }
  75264. return null;
  75265. };
  75266. return FxaaPostProcess;
  75267. }(BABYLON.PostProcess));
  75268. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75269. })(BABYLON || (BABYLON = {}));
  75270. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75271. var BABYLON;
  75272. (function (BABYLON) {
  75273. /**
  75274. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75275. */
  75276. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75277. __extends(ChromaticAberrationPostProcess, _super);
  75278. /**
  75279. * Creates a new instance ChromaticAberrationPostProcess
  75280. * @param name The name of the effect.
  75281. * @param screenWidth The width of the screen to apply the effect on.
  75282. * @param screenHeight The height of the screen to apply the effect on.
  75283. * @param options The required width/height ratio to downsize to before computing the render pass.
  75284. * @param camera The camera to apply the render pass to.
  75285. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75286. * @param engine The engine which the post process will be applied. (default: current engine)
  75287. * @param reusable If the post process can be reused on the same frame. (default: false)
  75288. * @param textureType Type of textures used when performing the post process. (default: 0)
  75289. * @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)
  75290. */
  75291. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75292. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75293. if (blockCompilation === void 0) { blockCompilation = false; }
  75294. 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;
  75295. /**
  75296. * The amount of seperation of rgb channels (default: 30)
  75297. */
  75298. _this.aberrationAmount = 30;
  75299. /**
  75300. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75301. */
  75302. _this.radialIntensity = 0;
  75303. /**
  75304. * 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))
  75305. */
  75306. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75307. /**
  75308. * 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))
  75309. */
  75310. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75311. _this.onApplyObservable.add(function (effect) {
  75312. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75313. effect.setFloat('screen_width', screenWidth);
  75314. effect.setFloat('screen_height', screenHeight);
  75315. effect.setFloat('radialIntensity', _this.radialIntensity);
  75316. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75317. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75318. });
  75319. return _this;
  75320. }
  75321. return ChromaticAberrationPostProcess;
  75322. }(BABYLON.PostProcess));
  75323. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75324. })(BABYLON || (BABYLON = {}));
  75325. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75326. var BABYLON;
  75327. (function (BABYLON) {
  75328. /**
  75329. * The GrainPostProcess adds noise to the image at mid luminance levels
  75330. */
  75331. var GrainPostProcess = /** @class */ (function (_super) {
  75332. __extends(GrainPostProcess, _super);
  75333. /**
  75334. * Creates a new instance of @see GrainPostProcess
  75335. * @param name The name of the effect.
  75336. * @param options The required width/height ratio to downsize to before computing the render pass.
  75337. * @param camera The camera to apply the render pass to.
  75338. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75339. * @param engine The engine which the post process will be applied. (default: current engine)
  75340. * @param reusable If the post process can be reused on the same frame. (default: false)
  75341. * @param textureType Type of textures used when performing the post process. (default: 0)
  75342. * @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)
  75343. */
  75344. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75345. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75346. if (blockCompilation === void 0) { blockCompilation = false; }
  75347. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75348. /**
  75349. * The intensity of the grain added (default: 30)
  75350. */
  75351. _this.intensity = 30;
  75352. /**
  75353. * If the grain should be randomized on every frame
  75354. */
  75355. _this.animated = false;
  75356. _this.onApplyObservable.add(function (effect) {
  75357. effect.setFloat('intensity', _this.intensity);
  75358. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75359. });
  75360. return _this;
  75361. }
  75362. return GrainPostProcess;
  75363. }(BABYLON.PostProcess));
  75364. BABYLON.GrainPostProcess = GrainPostProcess;
  75365. })(BABYLON || (BABYLON = {}));
  75366. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75367. var BABYLON;
  75368. (function (BABYLON) {
  75369. /**
  75370. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75371. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75372. */
  75373. var SharpenPostProcess = /** @class */ (function (_super) {
  75374. __extends(SharpenPostProcess, _super);
  75375. /**
  75376. * Creates a new instance ConvolutionPostProcess
  75377. * @param name The name of the effect.
  75378. * @param options The required width/height ratio to downsize to before computing the render pass.
  75379. * @param camera The camera to apply the render pass to.
  75380. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75381. * @param engine The engine which the post process will be applied. (default: current engine)
  75382. * @param reusable If the post process can be reused on the same frame. (default: false)
  75383. * @param textureType Type of textures used when performing the post process. (default: 0)
  75384. * @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)
  75385. */
  75386. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75387. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75388. if (blockCompilation === void 0) { blockCompilation = false; }
  75389. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75390. /**
  75391. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75392. */
  75393. _this.colorAmount = 1.0;
  75394. /**
  75395. * How much sharpness should be applied (default: 0.3)
  75396. */
  75397. _this.edgeAmount = 0.3;
  75398. _this.onApply = function (effect) {
  75399. effect.setFloat2("screenSize", _this.width, _this.height);
  75400. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75401. };
  75402. return _this;
  75403. }
  75404. return SharpenPostProcess;
  75405. }(BABYLON.PostProcess));
  75406. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75407. })(BABYLON || (BABYLON = {}));
  75408. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75409. var BABYLON;
  75410. (function (BABYLON) {
  75411. /**
  75412. * The Blur Post Process which blurs an image based on a kernel and direction.
  75413. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75414. */
  75415. var BlurPostProcess = /** @class */ (function (_super) {
  75416. __extends(BlurPostProcess, _super);
  75417. /**
  75418. * Creates a new instance BlurPostProcess
  75419. * @param name The name of the effect.
  75420. * @param direction The direction in which to blur the image.
  75421. * @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.
  75422. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75423. * @param camera The camera to apply the render pass to.
  75424. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75425. * @param engine The engine which the post process will be applied. (default: current engine)
  75426. * @param reusable If the post process can be reused on the same frame. (default: false)
  75427. * @param textureType Type of textures used when performing the post process. (default: 0)
  75428. * @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)
  75429. */
  75430. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75431. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75432. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75433. if (defines === void 0) { defines = ""; }
  75434. if (blockCompilation === void 0) { blockCompilation = false; }
  75435. 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;
  75436. _this.direction = direction;
  75437. _this.blockCompilation = blockCompilation;
  75438. _this._packedFloat = false;
  75439. _this._staticDefines = "";
  75440. _this._staticDefines = defines;
  75441. _this.onApplyObservable.add(function (effect) {
  75442. if (_this._outputTexture) {
  75443. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75444. }
  75445. else {
  75446. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75447. }
  75448. });
  75449. _this.kernel = kernel;
  75450. return _this;
  75451. }
  75452. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75453. /**
  75454. * Gets the length in pixels of the blur sample region
  75455. */
  75456. get: function () {
  75457. return this._idealKernel;
  75458. },
  75459. /**
  75460. * Sets the length in pixels of the blur sample region
  75461. */
  75462. set: function (v) {
  75463. if (this._idealKernel === v) {
  75464. return;
  75465. }
  75466. v = Math.max(v, 1);
  75467. this._idealKernel = v;
  75468. this._kernel = this._nearestBestKernel(v);
  75469. if (!this.blockCompilation) {
  75470. this._updateParameters();
  75471. }
  75472. },
  75473. enumerable: true,
  75474. configurable: true
  75475. });
  75476. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75477. /**
  75478. * Gets wether or not the blur is unpacking/repacking floats
  75479. */
  75480. get: function () {
  75481. return this._packedFloat;
  75482. },
  75483. /**
  75484. * Sets wether or not the blur needs to unpack/repack floats
  75485. */
  75486. set: function (v) {
  75487. if (this._packedFloat === v) {
  75488. return;
  75489. }
  75490. this._packedFloat = v;
  75491. if (!this.blockCompilation) {
  75492. this._updateParameters();
  75493. }
  75494. },
  75495. enumerable: true,
  75496. configurable: true
  75497. });
  75498. /**
  75499. * Updates the effect with the current post process compile time values and recompiles the shader.
  75500. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75501. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75502. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75503. * @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
  75504. * @param onCompiled Called when the shader has been compiled.
  75505. * @param onError Called if there is an error when compiling a shader.
  75506. */
  75507. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75508. if (defines === void 0) { defines = null; }
  75509. if (uniforms === void 0) { uniforms = null; }
  75510. if (samplers === void 0) { samplers = null; }
  75511. this._updateParameters(onCompiled, onError);
  75512. };
  75513. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75514. // Generate sampling offsets and weights
  75515. var N = this._kernel;
  75516. var centerIndex = (N - 1) / 2;
  75517. // Generate Gaussian sampling weights over kernel
  75518. var offsets = [];
  75519. var weights = [];
  75520. var totalWeight = 0;
  75521. for (var i = 0; i < N; i++) {
  75522. var u = i / (N - 1);
  75523. var w = this._gaussianWeight(u * 2.0 - 1);
  75524. offsets[i] = (i - centerIndex);
  75525. weights[i] = w;
  75526. totalWeight += w;
  75527. }
  75528. // Normalize weights
  75529. for (var i = 0; i < weights.length; i++) {
  75530. weights[i] /= totalWeight;
  75531. }
  75532. // Optimize: combine samples to take advantage of hardware linear sampling
  75533. // Walk from left to center, combining pairs (symmetrically)
  75534. var linearSamplingWeights = [];
  75535. var linearSamplingOffsets = [];
  75536. var linearSamplingMap = [];
  75537. for (var i = 0; i <= centerIndex; i += 2) {
  75538. var j = Math.min(i + 1, Math.floor(centerIndex));
  75539. var singleCenterSample = i === j;
  75540. if (singleCenterSample) {
  75541. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75542. }
  75543. else {
  75544. var sharedCell = j === centerIndex;
  75545. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75546. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75547. if (offsetLinear === 0) {
  75548. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75549. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75550. }
  75551. else {
  75552. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75553. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75554. }
  75555. }
  75556. }
  75557. for (var i = 0; i < linearSamplingMap.length; i++) {
  75558. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75559. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75560. }
  75561. // Replace with optimized
  75562. offsets = linearSamplingOffsets;
  75563. weights = linearSamplingWeights;
  75564. // Generate shaders
  75565. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75566. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75567. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75568. var defines = "";
  75569. defines += this._staticDefines;
  75570. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75571. if (this._staticDefines.indexOf("DOF") != -1) {
  75572. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75573. varyingCount--;
  75574. }
  75575. for (var i = 0; i < varyingCount; i++) {
  75576. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75577. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75578. }
  75579. var depCount = 0;
  75580. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75581. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75582. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75583. depCount++;
  75584. }
  75585. if (this.packedFloat) {
  75586. defines += "#define PACKEDFLOAT 1";
  75587. }
  75588. this.blockCompilation = false;
  75589. _super.prototype.updateEffect.call(this, defines, null, null, {
  75590. varyingCount: varyingCount,
  75591. depCount: depCount
  75592. }, onCompiled, onError);
  75593. };
  75594. /**
  75595. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75596. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75597. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75598. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75599. * The gaps between physical kernels are compensated for in the weighting of the samples
  75600. * @param idealKernel Ideal blur kernel.
  75601. * @return Nearest best kernel.
  75602. */
  75603. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75604. var v = Math.round(idealKernel);
  75605. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75606. var k = _a[_i];
  75607. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75608. return Math.max(k, 3);
  75609. }
  75610. }
  75611. return Math.max(v, 3);
  75612. };
  75613. /**
  75614. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75615. * @param x The point on the Gaussian distribution to sample.
  75616. * @return the value of the Gaussian function at x.
  75617. */
  75618. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75619. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75620. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75621. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75622. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75623. // truncated at around 1.3% of peak strength.
  75624. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75625. var sigma = (1 / 3);
  75626. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75627. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75628. var weight = (1.0 / denominator) * Math.exp(exponent);
  75629. return weight;
  75630. };
  75631. /**
  75632. * Generates a string that can be used as a floating point number in GLSL.
  75633. * @param x Value to print.
  75634. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75635. * @return GLSL float string.
  75636. */
  75637. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75638. if (decimalFigures === void 0) { decimalFigures = 8; }
  75639. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75640. };
  75641. return BlurPostProcess;
  75642. }(BABYLON.PostProcess));
  75643. BABYLON.BlurPostProcess = BlurPostProcess;
  75644. })(BABYLON || (BABYLON = {}));
  75645. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75646. var BABYLON;
  75647. (function (BABYLON) {
  75648. /**
  75649. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75650. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75651. * based on samples that have a large difference in distance than the center pixel.
  75652. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75653. */
  75654. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75655. __extends(DepthOfFieldBlurPostProcess, _super);
  75656. /**
  75657. * Creates a new instance CircleOfConfusionPostProcess
  75658. * @param name The name of the effect.
  75659. * @param scene The scene the effect belongs to.
  75660. * @param direction The direction the blur should be applied.
  75661. * @param kernel The size of the kernel used to blur.
  75662. * @param options The required width/height ratio to downsize to before computing the render pass.
  75663. * @param camera The camera to apply the render pass to.
  75664. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75665. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75666. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75667. * @param engine The engine which the post process will be applied. (default: current engine)
  75668. * @param reusable If the post process can be reused on the same frame. (default: false)
  75669. * @param textureType Type of textures used when performing the post process. (default: 0)
  75670. * @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)
  75671. */
  75672. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75673. if (imageToBlur === void 0) { imageToBlur = null; }
  75674. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75675. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75676. if (blockCompilation === void 0) { blockCompilation = false; }
  75677. 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;
  75678. _this.direction = direction;
  75679. _this.onApplyObservable.add(function (effect) {
  75680. if (imageToBlur != null) {
  75681. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75682. }
  75683. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75684. if (scene.activeCamera) {
  75685. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75686. }
  75687. });
  75688. return _this;
  75689. }
  75690. return DepthOfFieldBlurPostProcess;
  75691. }(BABYLON.BlurPostProcess));
  75692. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75693. })(BABYLON || (BABYLON = {}));
  75694. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75695. var BABYLON;
  75696. (function (BABYLON) {
  75697. /**
  75698. * Options to be set when merging outputs from the default pipeline.
  75699. */
  75700. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75701. function DepthOfFieldMergePostProcessOptions() {
  75702. }
  75703. return DepthOfFieldMergePostProcessOptions;
  75704. }());
  75705. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75706. /**
  75707. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75708. */
  75709. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75710. __extends(DepthOfFieldMergePostProcess, _super);
  75711. /**
  75712. * Creates a new instance of DepthOfFieldMergePostProcess
  75713. * @param name The name of the effect.
  75714. * @param originalFromInput Post process which's input will be used for the merge.
  75715. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75716. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75717. * @param options The required width/height ratio to downsize to before computing the render pass.
  75718. * @param camera The camera to apply the render pass to.
  75719. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75720. * @param engine The engine which the post process will be applied. (default: current engine)
  75721. * @param reusable If the post process can be reused on the same frame. (default: false)
  75722. * @param textureType Type of textures used when performing the post process. (default: 0)
  75723. * @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)
  75724. */
  75725. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75726. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75727. if (blockCompilation === void 0) { blockCompilation = false; }
  75728. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75729. _this.blurSteps = blurSteps;
  75730. _this.onApplyObservable.add(function (effect) {
  75731. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75732. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75733. blurSteps.forEach(function (step, index) {
  75734. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75735. });
  75736. });
  75737. if (!blockCompilation) {
  75738. _this.updateEffect();
  75739. }
  75740. return _this;
  75741. }
  75742. /**
  75743. * Updates the effect with the current post process compile time values and recompiles the shader.
  75744. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75745. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75746. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75747. * @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
  75748. * @param onCompiled Called when the shader has been compiled.
  75749. * @param onError Called if there is an error when compiling a shader.
  75750. */
  75751. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75752. if (defines === void 0) { defines = null; }
  75753. if (uniforms === void 0) { uniforms = null; }
  75754. if (samplers === void 0) { samplers = null; }
  75755. if (!defines) {
  75756. defines = "";
  75757. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75758. }
  75759. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75760. };
  75761. return DepthOfFieldMergePostProcess;
  75762. }(BABYLON.PostProcess));
  75763. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75764. })(BABYLON || (BABYLON = {}));
  75765. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75766. var BABYLON;
  75767. (function (BABYLON) {
  75768. /**
  75769. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75770. */
  75771. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75772. __extends(CircleOfConfusionPostProcess, _super);
  75773. /**
  75774. * Creates a new instance CircleOfConfusionPostProcess
  75775. * @param name The name of the effect.
  75776. * @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.
  75777. * @param options The required width/height ratio to downsize to before computing the render pass.
  75778. * @param camera The camera to apply the render pass to.
  75779. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75780. * @param engine The engine which the post process will be applied. (default: current engine)
  75781. * @param reusable If the post process can be reused on the same frame. (default: false)
  75782. * @param textureType Type of textures used when performing the post process. (default: 0)
  75783. * @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)
  75784. */
  75785. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75786. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75787. if (blockCompilation === void 0) { blockCompilation = false; }
  75788. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75789. /**
  75790. * 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.
  75791. */
  75792. _this.lensSize = 50;
  75793. /**
  75794. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75795. */
  75796. _this.fStop = 1.4;
  75797. /**
  75798. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75799. */
  75800. _this.focusDistance = 2000;
  75801. /**
  75802. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75803. */
  75804. _this.focalLength = 50;
  75805. _this._depthTexture = null;
  75806. _this._depthTexture = depthTexture;
  75807. _this.onApplyObservable.add(function (effect) {
  75808. if (!_this._depthTexture) {
  75809. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75810. return;
  75811. }
  75812. effect.setTexture("depthSampler", _this._depthTexture);
  75813. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75814. var aperture = _this.lensSize / _this.fStop;
  75815. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75816. effect.setFloat('focusDistance', _this.focusDistance);
  75817. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75818. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75819. });
  75820. return _this;
  75821. }
  75822. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75823. /**
  75824. * 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.
  75825. */
  75826. set: function (value) {
  75827. this._depthTexture = value;
  75828. },
  75829. enumerable: true,
  75830. configurable: true
  75831. });
  75832. return CircleOfConfusionPostProcess;
  75833. }(BABYLON.PostProcess));
  75834. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75835. })(BABYLON || (BABYLON = {}));
  75836. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75837. var BABYLON;
  75838. (function (BABYLON) {
  75839. /**
  75840. * Specifies the level of max blur that should be applied when using the depth of field effect
  75841. */
  75842. var DepthOfFieldEffectBlurLevel;
  75843. (function (DepthOfFieldEffectBlurLevel) {
  75844. /**
  75845. * Subtle blur
  75846. */
  75847. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75848. /**
  75849. * Medium blur
  75850. */
  75851. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75852. /**
  75853. * Large blur
  75854. */
  75855. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75856. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75857. ;
  75858. /**
  75859. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75860. */
  75861. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75862. __extends(DepthOfFieldEffect, _super);
  75863. /**
  75864. * Creates a new instance DepthOfFieldEffect
  75865. * @param scene The scene the effect belongs to.
  75866. * @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.
  75867. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75868. * @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)
  75869. */
  75870. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75871. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75872. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75873. if (blockCompilation === void 0) { blockCompilation = false; }
  75874. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75875. return _this._effects;
  75876. }, true) || this;
  75877. /**
  75878. * Internal post processes in depth of field effect
  75879. */
  75880. _this._effects = [];
  75881. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75882. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75883. // 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)
  75884. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75885. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75886. _this._depthOfFieldBlurY = [];
  75887. _this._depthOfFieldBlurX = [];
  75888. var blurCount = 1;
  75889. var kernelSize = 15;
  75890. switch (blurLevel) {
  75891. case DepthOfFieldEffectBlurLevel.High: {
  75892. blurCount = 3;
  75893. kernelSize = 51;
  75894. break;
  75895. }
  75896. case DepthOfFieldEffectBlurLevel.Medium: {
  75897. blurCount = 2;
  75898. kernelSize = 31;
  75899. break;
  75900. }
  75901. default: {
  75902. kernelSize = 15;
  75903. blurCount = 1;
  75904. break;
  75905. }
  75906. }
  75907. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75908. var ratio = 1.0;
  75909. for (var i = 0; i < blurCount; i++) {
  75910. 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);
  75911. blurY.autoClear = false;
  75912. ratio = 0.75 / Math.pow(2, i);
  75913. 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);
  75914. blurX.autoClear = false;
  75915. _this._depthOfFieldBlurY.push(blurY);
  75916. _this._depthOfFieldBlurX.push(blurX);
  75917. }
  75918. // Set all post processes on the effect.
  75919. _this._effects = [_this._circleOfConfusion];
  75920. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75921. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75922. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75923. }
  75924. // Merge blurred images with original image based on circleOfConfusion
  75925. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75926. _this._dofMerge.autoClear = false;
  75927. _this._effects.push(_this._dofMerge);
  75928. return _this;
  75929. }
  75930. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75931. get: function () {
  75932. return this._circleOfConfusion.focalLength;
  75933. },
  75934. /**
  75935. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75936. */
  75937. set: function (value) {
  75938. this._circleOfConfusion.focalLength = value;
  75939. },
  75940. enumerable: true,
  75941. configurable: true
  75942. });
  75943. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75944. get: function () {
  75945. return this._circleOfConfusion.fStop;
  75946. },
  75947. /**
  75948. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75949. */
  75950. set: function (value) {
  75951. this._circleOfConfusion.fStop = value;
  75952. },
  75953. enumerable: true,
  75954. configurable: true
  75955. });
  75956. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75957. get: function () {
  75958. return this._circleOfConfusion.focusDistance;
  75959. },
  75960. /**
  75961. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75962. */
  75963. set: function (value) {
  75964. this._circleOfConfusion.focusDistance = value;
  75965. },
  75966. enumerable: true,
  75967. configurable: true
  75968. });
  75969. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75970. get: function () {
  75971. return this._circleOfConfusion.lensSize;
  75972. },
  75973. /**
  75974. * 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.
  75975. */
  75976. set: function (value) {
  75977. this._circleOfConfusion.lensSize = value;
  75978. },
  75979. enumerable: true,
  75980. configurable: true
  75981. });
  75982. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75983. /**
  75984. * 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.
  75985. */
  75986. set: function (value) {
  75987. this._circleOfConfusion.depthTexture = value;
  75988. },
  75989. enumerable: true,
  75990. configurable: true
  75991. });
  75992. /**
  75993. * Disposes each of the internal effects for a given camera.
  75994. * @param camera The camera to dispose the effect on.
  75995. */
  75996. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75997. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75998. this._effects[effectIndex].dispose(camera);
  75999. }
  76000. };
  76001. /**
  76002. * Internal
  76003. */
  76004. DepthOfFieldEffect.prototype._updateEffects = function () {
  76005. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76006. this._effects[effectIndex].updateEffect();
  76007. }
  76008. };
  76009. /**
  76010. * Internal
  76011. * @returns if all the contained post processes are ready.
  76012. */
  76013. DepthOfFieldEffect.prototype._isReady = function () {
  76014. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76015. if (!this._effects[effectIndex].isReady()) {
  76016. return false;
  76017. }
  76018. }
  76019. return true;
  76020. };
  76021. return DepthOfFieldEffect;
  76022. }(BABYLON.PostProcessRenderEffect));
  76023. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76024. })(BABYLON || (BABYLON = {}));
  76025. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76026. var BABYLON;
  76027. (function (BABYLON) {
  76028. /**
  76029. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76030. */
  76031. var BloomMergePostProcess = /** @class */ (function (_super) {
  76032. __extends(BloomMergePostProcess, _super);
  76033. /**
  76034. * Creates a new instance of @see BloomMergePostProcess
  76035. * @param name The name of the effect.
  76036. * @param originalFromInput Post process which's input will be used for the merge.
  76037. * @param blurred Blurred highlights post process which's output will be used.
  76038. * @param weight Weight of the bloom to be added to the original input.
  76039. * @param options The required width/height ratio to downsize to before computing the render pass.
  76040. * @param camera The camera to apply the render pass to.
  76041. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76042. * @param engine The engine which the post process will be applied. (default: current engine)
  76043. * @param reusable If the post process can be reused on the same frame. (default: false)
  76044. * @param textureType Type of textures used when performing the post process. (default: 0)
  76045. * @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)
  76046. */
  76047. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76048. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76049. if (blockCompilation === void 0) { blockCompilation = false; }
  76050. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76051. _this.weight = weight;
  76052. _this.onApplyObservable.add(function (effect) {
  76053. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76054. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76055. effect.setFloat("bloomWeight", _this.weight);
  76056. });
  76057. if (!blockCompilation) {
  76058. _this.updateEffect();
  76059. }
  76060. return _this;
  76061. }
  76062. return BloomMergePostProcess;
  76063. }(BABYLON.PostProcess));
  76064. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76065. })(BABYLON || (BABYLON = {}));
  76066. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76067. var BABYLON;
  76068. (function (BABYLON) {
  76069. /**
  76070. * 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.
  76071. */
  76072. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76073. __extends(ExtractHighlightsPostProcess, _super);
  76074. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76075. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76076. if (blockCompilation === void 0) { blockCompilation = false; }
  76077. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76078. /**
  76079. * The luminance threshold, pixels below this value will be set to black.
  76080. */
  76081. _this.threshold = 0.9;
  76082. /**
  76083. * Internal
  76084. */
  76085. _this._exposure = 1;
  76086. /**
  76087. * Post process which has the input texture to be used when performing highlight extraction
  76088. */
  76089. _this._inputPostProcess = null;
  76090. _this.onApplyObservable.add(function (effect) {
  76091. if (_this._inputPostProcess) {
  76092. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76093. }
  76094. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76095. effect.setFloat('exposure', _this._exposure);
  76096. });
  76097. return _this;
  76098. }
  76099. return ExtractHighlightsPostProcess;
  76100. }(BABYLON.PostProcess));
  76101. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76102. })(BABYLON || (BABYLON = {}));
  76103. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76104. var BABYLON;
  76105. (function (BABYLON) {
  76106. /**
  76107. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76108. */
  76109. var BloomEffect = /** @class */ (function (_super) {
  76110. __extends(BloomEffect, _super);
  76111. /**
  76112. * Creates a new instance of @see BloomEffect
  76113. * @param scene The scene the effect belongs to.
  76114. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76115. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76116. * @param bloomWeight The the strength of bloom.
  76117. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76118. * @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)
  76119. */
  76120. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76121. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76122. if (blockCompilation === void 0) { blockCompilation = false; }
  76123. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76124. return _this._effects;
  76125. }, true) || this;
  76126. _this.bloomScale = bloomScale;
  76127. /**
  76128. * Internal
  76129. */
  76130. _this._effects = [];
  76131. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76132. _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);
  76133. _this._blurX.alwaysForcePOT = true;
  76134. _this._blurX.autoClear = false;
  76135. _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);
  76136. _this._blurY.alwaysForcePOT = true;
  76137. _this._blurY.autoClear = false;
  76138. _this.kernel = bloomKernel;
  76139. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76140. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76141. _this._merge.autoClear = false;
  76142. _this._effects.push(_this._merge);
  76143. return _this;
  76144. }
  76145. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76146. /**
  76147. * The luminance threshold to find bright areas of the image to bloom.
  76148. */
  76149. get: function () {
  76150. return this._downscale.threshold;
  76151. },
  76152. set: function (value) {
  76153. this._downscale.threshold = value;
  76154. },
  76155. enumerable: true,
  76156. configurable: true
  76157. });
  76158. Object.defineProperty(BloomEffect.prototype, "weight", {
  76159. /**
  76160. * The strength of the bloom.
  76161. */
  76162. get: function () {
  76163. return this._merge.weight;
  76164. },
  76165. set: function (value) {
  76166. this._merge.weight = value;
  76167. },
  76168. enumerable: true,
  76169. configurable: true
  76170. });
  76171. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76172. /**
  76173. * Specifies the size of the bloom blur kernel, relative to the final output size
  76174. */
  76175. get: function () {
  76176. return this._blurX.kernel / this.bloomScale;
  76177. },
  76178. set: function (value) {
  76179. this._blurX.kernel = value * this.bloomScale;
  76180. this._blurY.kernel = value * this.bloomScale;
  76181. },
  76182. enumerable: true,
  76183. configurable: true
  76184. });
  76185. /**
  76186. * Disposes each of the internal effects for a given camera.
  76187. * @param camera The camera to dispose the effect on.
  76188. */
  76189. BloomEffect.prototype.disposeEffects = function (camera) {
  76190. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76191. this._effects[effectIndex].dispose(camera);
  76192. }
  76193. };
  76194. /**
  76195. * Internal
  76196. */
  76197. BloomEffect.prototype._updateEffects = function () {
  76198. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76199. this._effects[effectIndex].updateEffect();
  76200. }
  76201. };
  76202. /**
  76203. * Internal
  76204. * @returns if all the contained post processes are ready.
  76205. */
  76206. BloomEffect.prototype._isReady = function () {
  76207. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76208. if (!this._effects[effectIndex].isReady()) {
  76209. return false;
  76210. }
  76211. }
  76212. return true;
  76213. };
  76214. return BloomEffect;
  76215. }(BABYLON.PostProcessRenderEffect));
  76216. BABYLON.BloomEffect = BloomEffect;
  76217. })(BABYLON || (BABYLON = {}));
  76218. //# sourceMappingURL=babylon.bloomEffect.js.map
  76219. var BABYLON;
  76220. (function (BABYLON) {
  76221. /**
  76222. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76223. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76224. */
  76225. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76226. __extends(DefaultRenderingPipeline, _super);
  76227. /**
  76228. * @constructor
  76229. * @param {string} name - The rendering pipeline name (default: "")
  76230. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76231. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76232. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76233. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76234. */
  76235. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76236. if (name === void 0) { name = ""; }
  76237. if (hdr === void 0) { hdr = true; }
  76238. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76239. if (automaticBuild === void 0) { automaticBuild = true; }
  76240. var _this = _super.call(this, scene.getEngine(), name) || this;
  76241. _this._camerasToBeAttached = [];
  76242. /**
  76243. * ID of the sharpen post process,
  76244. */
  76245. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76246. /**
  76247. * ID of the image processing post process;
  76248. */
  76249. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76250. /**
  76251. * ID of the Fast Approximate Anti-Aliasing post process;
  76252. */
  76253. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76254. /**
  76255. * ID of the chromatic aberration post process,
  76256. */
  76257. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76258. /**
  76259. * ID of the grain post process
  76260. */
  76261. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76262. /**
  76263. * Glow post process which adds a glow to emmisive areas of the image
  76264. */
  76265. _this._glowLayer = null;
  76266. /**
  76267. * Animations which can be used to tweak settings over a period of time
  76268. */
  76269. _this.animations = [];
  76270. _this._imageProcessingConfigurationObserver = null;
  76271. // Values
  76272. _this._sharpenEnabled = false;
  76273. _this._bloomEnabled = false;
  76274. _this._depthOfFieldEnabled = false;
  76275. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76276. _this._fxaaEnabled = false;
  76277. _this._imageProcessingEnabled = true;
  76278. _this._bloomScale = 0.5;
  76279. _this._chromaticAberrationEnabled = false;
  76280. _this._grainEnabled = false;
  76281. _this._buildAllowed = true;
  76282. _this._resizeObserver = null;
  76283. _this._hardwareScaleLevel = 1.0;
  76284. _this._bloomKernel = 64;
  76285. /**
  76286. * Specifies the weight of the bloom in the final rendering
  76287. */
  76288. _this._bloomWeight = 0.15;
  76289. /**
  76290. * Specifies the luma threshold for the area that will be blurred by the bloom
  76291. */
  76292. _this._bloomThreshold = 0.9;
  76293. _this._samples = 1;
  76294. _this._hasCleared = false;
  76295. _this._prevPostProcess = null;
  76296. _this._prevPrevPostProcess = null;
  76297. _this._cameras = cameras || scene.cameras;
  76298. _this._camerasToBeAttached = _this._cameras.slice();
  76299. _this._buildAllowed = automaticBuild;
  76300. // Initialize
  76301. _this._scene = scene;
  76302. var caps = _this._scene.getEngine().getCaps();
  76303. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76304. // Misc
  76305. if (_this._hdr) {
  76306. if (caps.textureHalfFloatRender) {
  76307. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76308. }
  76309. else if (caps.textureFloatRender) {
  76310. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76311. }
  76312. }
  76313. else {
  76314. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76315. }
  76316. // Attach
  76317. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76318. var engine = _this._scene.getEngine();
  76319. // Create post processes before hand so they can be modified before enabled.
  76320. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76321. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76322. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76323. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76324. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76325. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76326. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76327. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76328. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76329. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76330. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76331. _this.bloomKernel = _this.bloomKernel;
  76332. });
  76333. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76334. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76335. });
  76336. _this._buildPipeline();
  76337. return _this;
  76338. }
  76339. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76340. get: function () {
  76341. return this._sharpenEnabled;
  76342. },
  76343. /**
  76344. * Enable or disable the sharpen process from the pipeline
  76345. */
  76346. set: function (enabled) {
  76347. if (this._sharpenEnabled === enabled) {
  76348. return;
  76349. }
  76350. this._sharpenEnabled = enabled;
  76351. this._buildPipeline();
  76352. },
  76353. enumerable: true,
  76354. configurable: true
  76355. });
  76356. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76357. /**
  76358. * Specifies the size of the bloom blur kernel, relative to the final output size
  76359. */
  76360. get: function () {
  76361. return this._bloomKernel;
  76362. },
  76363. set: function (value) {
  76364. this._bloomKernel = value;
  76365. this.bloom.kernel = value / this._hardwareScaleLevel;
  76366. },
  76367. enumerable: true,
  76368. configurable: true
  76369. });
  76370. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76371. get: function () {
  76372. return this._bloomWeight;
  76373. },
  76374. /**
  76375. * The strength of the bloom.
  76376. */
  76377. set: function (value) {
  76378. if (this._bloomWeight === value) {
  76379. return;
  76380. }
  76381. this.bloom.weight = value;
  76382. this._bloomWeight = value;
  76383. },
  76384. enumerable: true,
  76385. configurable: true
  76386. });
  76387. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76388. get: function () {
  76389. return this._bloomThreshold;
  76390. },
  76391. /**
  76392. * The strength of the bloom.
  76393. */
  76394. set: function (value) {
  76395. if (this._bloomThreshold === value) {
  76396. return;
  76397. }
  76398. this.bloom.threshold = value;
  76399. this._bloomThreshold = value;
  76400. },
  76401. enumerable: true,
  76402. configurable: true
  76403. });
  76404. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76405. get: function () {
  76406. return this._bloomScale;
  76407. },
  76408. /**
  76409. * The scale of the bloom, lower value will provide better performance.
  76410. */
  76411. set: function (value) {
  76412. if (this._bloomScale === value) {
  76413. return;
  76414. }
  76415. this._bloomScale = value;
  76416. // recreate bloom and dispose old as this setting is not dynamic
  76417. this._rebuildBloom();
  76418. this._buildPipeline();
  76419. },
  76420. enumerable: true,
  76421. configurable: true
  76422. });
  76423. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76424. get: function () {
  76425. return this._bloomEnabled;
  76426. },
  76427. /**
  76428. * Enable or disable the bloom from the pipeline
  76429. */
  76430. set: function (enabled) {
  76431. if (this._bloomEnabled === enabled) {
  76432. return;
  76433. }
  76434. this._bloomEnabled = enabled;
  76435. this._buildPipeline();
  76436. },
  76437. enumerable: true,
  76438. configurable: true
  76439. });
  76440. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76441. // recreate bloom and dispose old as this setting is not dynamic
  76442. var oldBloom = this.bloom;
  76443. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76444. this.bloom.threshold = oldBloom.threshold;
  76445. for (var i = 0; i < this._cameras.length; i++) {
  76446. oldBloom.disposeEffects(this._cameras[i]);
  76447. }
  76448. };
  76449. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76450. /**
  76451. * If the depth of field is enabled.
  76452. */
  76453. get: function () {
  76454. return this._depthOfFieldEnabled;
  76455. },
  76456. set: function (enabled) {
  76457. if (this._depthOfFieldEnabled === enabled) {
  76458. return;
  76459. }
  76460. this._depthOfFieldEnabled = enabled;
  76461. this._buildPipeline();
  76462. },
  76463. enumerable: true,
  76464. configurable: true
  76465. });
  76466. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76467. /**
  76468. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76469. */
  76470. get: function () {
  76471. return this._depthOfFieldBlurLevel;
  76472. },
  76473. set: function (value) {
  76474. if (this._depthOfFieldBlurLevel === value) {
  76475. return;
  76476. }
  76477. this._depthOfFieldBlurLevel = value;
  76478. // recreate dof and dispose old as this setting is not dynamic
  76479. var oldDof = this.depthOfField;
  76480. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76481. this.depthOfField.focalLength = oldDof.focalLength;
  76482. this.depthOfField.focusDistance = oldDof.focusDistance;
  76483. this.depthOfField.fStop = oldDof.fStop;
  76484. this.depthOfField.lensSize = oldDof.lensSize;
  76485. for (var i = 0; i < this._cameras.length; i++) {
  76486. oldDof.disposeEffects(this._cameras[i]);
  76487. }
  76488. this._buildPipeline();
  76489. },
  76490. enumerable: true,
  76491. configurable: true
  76492. });
  76493. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76494. get: function () {
  76495. return this._fxaaEnabled;
  76496. },
  76497. /**
  76498. * If the anti aliasing is enabled.
  76499. */
  76500. set: function (enabled) {
  76501. if (this._fxaaEnabled === enabled) {
  76502. return;
  76503. }
  76504. this._fxaaEnabled = enabled;
  76505. this._buildPipeline();
  76506. },
  76507. enumerable: true,
  76508. configurable: true
  76509. });
  76510. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76511. get: function () {
  76512. return this._samples;
  76513. },
  76514. /**
  76515. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76516. */
  76517. set: function (sampleCount) {
  76518. if (this._samples === sampleCount) {
  76519. return;
  76520. }
  76521. this._samples = sampleCount;
  76522. this._buildPipeline();
  76523. },
  76524. enumerable: true,
  76525. configurable: true
  76526. });
  76527. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76528. get: function () {
  76529. return this._imageProcessingEnabled;
  76530. },
  76531. /**
  76532. * If image processing is enabled.
  76533. */
  76534. set: function (enabled) {
  76535. if (this._imageProcessingEnabled === enabled) {
  76536. return;
  76537. }
  76538. this._imageProcessingEnabled = enabled;
  76539. this._buildPipeline();
  76540. },
  76541. enumerable: true,
  76542. configurable: true
  76543. });
  76544. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76545. get: function () {
  76546. return this._glowLayer == null;
  76547. },
  76548. /**
  76549. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76550. */
  76551. set: function (enabled) {
  76552. if (enabled && !this._glowLayer) {
  76553. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76554. }
  76555. else if (!enabled && this._glowLayer) {
  76556. this._glowLayer.dispose();
  76557. this._glowLayer = null;
  76558. }
  76559. },
  76560. enumerable: true,
  76561. configurable: true
  76562. });
  76563. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76564. get: function () {
  76565. return this._chromaticAberrationEnabled;
  76566. },
  76567. /**
  76568. * Enable or disable the chromaticAberration process from the pipeline
  76569. */
  76570. set: function (enabled) {
  76571. if (this._chromaticAberrationEnabled === enabled) {
  76572. return;
  76573. }
  76574. this._chromaticAberrationEnabled = enabled;
  76575. this._buildPipeline();
  76576. },
  76577. enumerable: true,
  76578. configurable: true
  76579. });
  76580. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76581. get: function () {
  76582. return this._grainEnabled;
  76583. },
  76584. /**
  76585. * Enable or disable the grain process from the pipeline
  76586. */
  76587. set: function (enabled) {
  76588. if (this._grainEnabled === enabled) {
  76589. return;
  76590. }
  76591. this._grainEnabled = enabled;
  76592. this._buildPipeline();
  76593. },
  76594. enumerable: true,
  76595. configurable: true
  76596. });
  76597. /**
  76598. * Force the compilation of the entire pipeline.
  76599. */
  76600. DefaultRenderingPipeline.prototype.prepare = function () {
  76601. var previousState = this._buildAllowed;
  76602. this._buildAllowed = true;
  76603. this._buildPipeline();
  76604. this._buildAllowed = previousState;
  76605. };
  76606. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76607. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76608. if (this._hasCleared) {
  76609. postProcess.autoClear = false;
  76610. }
  76611. else {
  76612. postProcess.autoClear = true;
  76613. this._scene.autoClear = false;
  76614. this._hasCleared = true;
  76615. }
  76616. if (!skipTextureSharing) {
  76617. if (this._prevPrevPostProcess) {
  76618. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76619. }
  76620. else {
  76621. postProcess.useOwnOutput();
  76622. }
  76623. if (this._prevPostProcess) {
  76624. this._prevPrevPostProcess = this._prevPostProcess;
  76625. }
  76626. this._prevPostProcess = postProcess;
  76627. }
  76628. };
  76629. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76630. var _this = this;
  76631. if (!this._buildAllowed) {
  76632. return;
  76633. }
  76634. this._scene.autoClear = true;
  76635. var engine = this._scene.getEngine();
  76636. this._disposePostProcesses();
  76637. if (this._cameras !== null) {
  76638. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76639. // get back cameras to be used to reattach pipeline
  76640. this._cameras = this._camerasToBeAttached.slice();
  76641. }
  76642. this._reset();
  76643. this._prevPostProcess = null;
  76644. this._prevPrevPostProcess = null;
  76645. this._hasCleared = false;
  76646. if (this.depthOfFieldEnabled) {
  76647. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76648. this.depthOfField.depthTexture = depthTexture;
  76649. if (!this.depthOfField._isReady()) {
  76650. this.depthOfField._updateEffects();
  76651. }
  76652. this.addEffect(this.depthOfField);
  76653. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76654. }
  76655. if (this.bloomEnabled) {
  76656. if (!this.bloom._isReady()) {
  76657. this.bloom._updateEffects();
  76658. }
  76659. this.addEffect(this.bloom);
  76660. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76661. }
  76662. if (this._imageProcessingEnabled) {
  76663. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76664. if (this._hdr) {
  76665. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76666. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76667. }
  76668. else {
  76669. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76670. }
  76671. }
  76672. if (this.sharpenEnabled) {
  76673. if (!this.sharpen.isReady()) {
  76674. this.sharpen.updateEffect();
  76675. }
  76676. this.addEffect(this._sharpenEffect);
  76677. this._setAutoClearAndTextureSharing(this.sharpen);
  76678. }
  76679. if (this.grainEnabled) {
  76680. if (!this.grain.isReady()) {
  76681. this.grain.updateEffect();
  76682. }
  76683. this.addEffect(this._grainEffect);
  76684. this._setAutoClearAndTextureSharing(this.grain);
  76685. }
  76686. if (this.chromaticAberrationEnabled) {
  76687. if (!this.chromaticAberration.isReady()) {
  76688. this.chromaticAberration.updateEffect();
  76689. }
  76690. this.addEffect(this._chromaticAberrationEffect);
  76691. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76692. }
  76693. if (this.fxaaEnabled) {
  76694. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76695. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76696. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76697. }
  76698. if (this._cameras !== null) {
  76699. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76700. }
  76701. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76702. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76703. }
  76704. };
  76705. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76706. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76707. for (var i = 0; i < this._cameras.length; i++) {
  76708. var camera = this._cameras[i];
  76709. if (this.imageProcessing) {
  76710. this.imageProcessing.dispose(camera);
  76711. }
  76712. if (this.fxaa) {
  76713. this.fxaa.dispose(camera);
  76714. }
  76715. // These are created in the constructor and should not be disposed on every pipeline change
  76716. if (disposeNonRecreated) {
  76717. if (this.sharpen) {
  76718. this.sharpen.dispose(camera);
  76719. }
  76720. if (this.depthOfField) {
  76721. this.depthOfField.disposeEffects(camera);
  76722. }
  76723. if (this.bloom) {
  76724. this.bloom.disposeEffects(camera);
  76725. }
  76726. if (this.chromaticAberration) {
  76727. this.chromaticAberration.dispose(camera);
  76728. }
  76729. if (this.grain) {
  76730. this.grain.dispose(camera);
  76731. }
  76732. if (this._glowLayer) {
  76733. this._glowLayer.dispose();
  76734. }
  76735. }
  76736. }
  76737. this.imageProcessing = null;
  76738. this.fxaa = null;
  76739. if (disposeNonRecreated) {
  76740. this.sharpen = null;
  76741. this._sharpenEffect = null;
  76742. this.depthOfField = null;
  76743. this.bloom = null;
  76744. this.chromaticAberration = null;
  76745. this._chromaticAberrationEffect = null;
  76746. this.grain = null;
  76747. this._grainEffect = null;
  76748. this._glowLayer = null;
  76749. }
  76750. };
  76751. /**
  76752. * Adds a camera to the pipeline
  76753. * @param camera the camera to be added
  76754. */
  76755. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  76756. this._camerasToBeAttached.push(camera);
  76757. this._buildPipeline();
  76758. };
  76759. /**
  76760. * Removes a camera from the pipeline
  76761. * @param camera the camera to remove
  76762. */
  76763. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  76764. var index = this._camerasToBeAttached.indexOf(camera);
  76765. this._camerasToBeAttached.splice(index, 1);
  76766. this._buildPipeline();
  76767. };
  76768. /**
  76769. * Dispose of the pipeline and stop all post processes
  76770. */
  76771. DefaultRenderingPipeline.prototype.dispose = function () {
  76772. this._disposePostProcesses(true);
  76773. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76774. this._scene.autoClear = true;
  76775. if (this._resizeObserver) {
  76776. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76777. this._resizeObserver = null;
  76778. }
  76779. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76780. _super.prototype.dispose.call(this);
  76781. };
  76782. /**
  76783. * Serialize the rendering pipeline (Used when exporting)
  76784. * @returns the serialized object
  76785. */
  76786. DefaultRenderingPipeline.prototype.serialize = function () {
  76787. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76788. serializationObject.customType = "DefaultRenderingPipeline";
  76789. return serializationObject;
  76790. };
  76791. /**
  76792. * Parse the serialized pipeline
  76793. * @param source Source pipeline.
  76794. * @param scene The scene to load the pipeline to.
  76795. * @param rootUrl The URL of the serialized pipeline.
  76796. * @returns An instantiated pipeline from the serialized object.
  76797. */
  76798. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76799. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76800. };
  76801. __decorate([
  76802. BABYLON.serialize()
  76803. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76804. __decorate([
  76805. BABYLON.serialize()
  76806. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76807. __decorate([
  76808. BABYLON.serialize()
  76809. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76810. __decorate([
  76811. BABYLON.serialize()
  76812. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76813. __decorate([
  76814. BABYLON.serialize()
  76815. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76816. __decorate([
  76817. BABYLON.serialize()
  76818. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76819. __decorate([
  76820. BABYLON.serialize()
  76821. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76822. __decorate([
  76823. BABYLON.serialize()
  76824. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76825. __decorate([
  76826. BABYLON.serialize()
  76827. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76828. __decorate([
  76829. BABYLON.serialize()
  76830. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76831. __decorate([
  76832. BABYLON.serialize()
  76833. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76834. __decorate([
  76835. BABYLON.serialize()
  76836. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76837. __decorate([
  76838. BABYLON.serialize()
  76839. ], DefaultRenderingPipeline.prototype, "samples", null);
  76840. __decorate([
  76841. BABYLON.serialize()
  76842. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76843. __decorate([
  76844. BABYLON.serialize()
  76845. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76846. __decorate([
  76847. BABYLON.serialize()
  76848. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76849. __decorate([
  76850. BABYLON.serialize()
  76851. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76852. return DefaultRenderingPipeline;
  76853. }(BABYLON.PostProcessRenderPipeline));
  76854. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76855. })(BABYLON || (BABYLON = {}));
  76856. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76857. var BABYLON;
  76858. (function (BABYLON) {
  76859. /**
  76860. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76861. */
  76862. var GeometryBufferRenderer = /** @class */ (function () {
  76863. /**
  76864. * Creates a new G Buffer for the scene
  76865. * @param scene The scene the buffer belongs to
  76866. * @param ratio How big is the buffer related to the main canvas.
  76867. */
  76868. function GeometryBufferRenderer(scene, ratio) {
  76869. if (ratio === void 0) { ratio = 1; }
  76870. this._enablePosition = false;
  76871. this._scene = scene;
  76872. this._ratio = ratio;
  76873. // Render target
  76874. this._createRenderTargets();
  76875. }
  76876. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76877. /**
  76878. * Set the render list (meshes to be rendered) used in the G buffer.
  76879. */
  76880. set: function (meshes) {
  76881. this._multiRenderTarget.renderList = meshes;
  76882. },
  76883. enumerable: true,
  76884. configurable: true
  76885. });
  76886. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76887. /**
  76888. * Gets wether or not G buffer are supported by the running hardware.
  76889. * This requires draw buffer supports
  76890. */
  76891. get: function () {
  76892. return this._multiRenderTarget.isSupported;
  76893. },
  76894. enumerable: true,
  76895. configurable: true
  76896. });
  76897. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76898. /**
  76899. * Gets wether or not position are enabled for the G buffer.
  76900. */
  76901. get: function () {
  76902. return this._enablePosition;
  76903. },
  76904. /**
  76905. * Sets wether or not position are enabled for the G buffer.
  76906. */
  76907. set: function (enable) {
  76908. this._enablePosition = enable;
  76909. this.dispose();
  76910. this._createRenderTargets();
  76911. },
  76912. enumerable: true,
  76913. configurable: true
  76914. });
  76915. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76916. /**
  76917. * Gets the scene associated with the buffer.
  76918. */
  76919. get: function () {
  76920. return this._scene;
  76921. },
  76922. enumerable: true,
  76923. configurable: true
  76924. });
  76925. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76926. /**
  76927. * Gets the ratio used by the buffer during its creation.
  76928. * How big is the buffer related to the main canvas.
  76929. */
  76930. get: function () {
  76931. return this._ratio;
  76932. },
  76933. enumerable: true,
  76934. configurable: true
  76935. });
  76936. /**
  76937. * Checks wether everything is ready to render a submesh to the G buffer.
  76938. * @param subMesh the submesh to check readiness for
  76939. * @param useInstances is the mesh drawn using instance or not
  76940. * @returns true if ready otherwise false
  76941. */
  76942. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76943. var material = subMesh.getMaterial();
  76944. if (material && material.disableDepthWrite) {
  76945. return false;
  76946. }
  76947. var defines = [];
  76948. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76949. var mesh = subMesh.getMesh();
  76950. // Alpha test
  76951. if (material && material.needAlphaTesting()) {
  76952. defines.push("#define ALPHATEST");
  76953. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76954. attribs.push(BABYLON.VertexBuffer.UVKind);
  76955. defines.push("#define UV1");
  76956. }
  76957. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76958. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76959. defines.push("#define UV2");
  76960. }
  76961. }
  76962. // Buffers
  76963. if (this._enablePosition) {
  76964. defines.push("#define POSITION");
  76965. }
  76966. // Bones
  76967. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76968. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76969. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76970. if (mesh.numBoneInfluencers > 4) {
  76971. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76972. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76973. }
  76974. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76975. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76976. }
  76977. else {
  76978. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76979. }
  76980. // Instances
  76981. if (useInstances) {
  76982. defines.push("#define INSTANCES");
  76983. attribs.push("world0");
  76984. attribs.push("world1");
  76985. attribs.push("world2");
  76986. attribs.push("world3");
  76987. }
  76988. // Get correct effect
  76989. var join = defines.join("\n");
  76990. if (this._cachedDefines !== join) {
  76991. this._cachedDefines = join;
  76992. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76993. }
  76994. return this._effect.isReady();
  76995. };
  76996. /**
  76997. * Gets the current underlying G Buffer.
  76998. * @returns the buffer
  76999. */
  77000. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77001. return this._multiRenderTarget;
  77002. };
  77003. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77004. /**
  77005. * Gets the number of samples used to render the buffer (anti aliasing).
  77006. */
  77007. get: function () {
  77008. return this._multiRenderTarget.samples;
  77009. },
  77010. /**
  77011. * Sets the number of samples used to render the buffer (anti aliasing).
  77012. */
  77013. set: function (value) {
  77014. this._multiRenderTarget.samples = value;
  77015. },
  77016. enumerable: true,
  77017. configurable: true
  77018. });
  77019. /**
  77020. * Disposes the renderer and frees up associated resources.
  77021. */
  77022. GeometryBufferRenderer.prototype.dispose = function () {
  77023. this.getGBuffer().dispose();
  77024. };
  77025. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77026. var _this = this;
  77027. var engine = this._scene.getEngine();
  77028. var count = this._enablePosition ? 3 : 2;
  77029. 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 });
  77030. if (!this.isSupported) {
  77031. return;
  77032. }
  77033. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77034. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77035. this._multiRenderTarget.refreshRate = 1;
  77036. this._multiRenderTarget.renderParticles = false;
  77037. this._multiRenderTarget.renderList = null;
  77038. // set default depth value to 1.0 (far away)
  77039. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77040. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77041. });
  77042. // Custom render function
  77043. var renderSubMesh = function (subMesh) {
  77044. var mesh = subMesh.getRenderingMesh();
  77045. var scene = _this._scene;
  77046. var engine = scene.getEngine();
  77047. var material = subMesh.getMaterial();
  77048. if (!material) {
  77049. return;
  77050. }
  77051. // Culling
  77052. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77053. // Managing instances
  77054. var batch = mesh._getInstancesRenderList(subMesh._id);
  77055. if (batch.mustReturn) {
  77056. return;
  77057. }
  77058. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77059. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77060. engine.enableEffect(_this._effect);
  77061. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77062. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77063. _this._effect.setMatrix("view", scene.getViewMatrix());
  77064. // Alpha test
  77065. if (material && material.needAlphaTesting()) {
  77066. var alphaTexture = material.getAlphaTestTexture();
  77067. if (alphaTexture) {
  77068. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77069. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77070. }
  77071. }
  77072. // Bones
  77073. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77074. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77075. }
  77076. // Draw
  77077. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77078. }
  77079. };
  77080. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77081. var index;
  77082. if (depthOnlySubMeshes.length) {
  77083. engine.setColorWrite(false);
  77084. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77085. renderSubMesh(depthOnlySubMeshes.data[index]);
  77086. }
  77087. engine.setColorWrite(true);
  77088. }
  77089. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77090. renderSubMesh(opaqueSubMeshes.data[index]);
  77091. }
  77092. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77093. renderSubMesh(alphaTestSubMeshes.data[index]);
  77094. }
  77095. };
  77096. };
  77097. return GeometryBufferRenderer;
  77098. }());
  77099. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77100. })(BABYLON || (BABYLON = {}));
  77101. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77102. var BABYLON;
  77103. (function (BABYLON) {
  77104. /**
  77105. * This groups together the common properties used for image processing either in direct forward pass
  77106. * or through post processing effect depending on the use of the image processing pipeline in your scene
  77107. * or not.
  77108. */
  77109. var ImageProcessingConfiguration = /** @class */ (function () {
  77110. function ImageProcessingConfiguration() {
  77111. /**
  77112. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  77113. */
  77114. this.colorCurves = new BABYLON.ColorCurves();
  77115. this._colorCurvesEnabled = false;
  77116. this._colorGradingEnabled = false;
  77117. this._colorGradingWithGreenDepth = true;
  77118. this._colorGradingBGR = true;
  77119. this._exposure = 1.0;
  77120. this._toneMappingEnabled = false;
  77121. this._contrast = 1.0;
  77122. /**
  77123. * Vignette stretch size.
  77124. */
  77125. this.vignetteStretch = 0;
  77126. /**
  77127. * Vignette centre X Offset.
  77128. */
  77129. this.vignetteCentreX = 0;
  77130. /**
  77131. * Vignette centre Y Offset.
  77132. */
  77133. this.vignetteCentreY = 0;
  77134. /**
  77135. * Vignette weight or intensity of the vignette effect.
  77136. */
  77137. this.vignetteWeight = 1.5;
  77138. /**
  77139. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77140. * if vignetteEnabled is set to true.
  77141. */
  77142. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77143. /**
  77144. * Camera field of view used by the Vignette effect.
  77145. */
  77146. this.vignetteCameraFov = 0.5;
  77147. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  77148. this._vignetteEnabled = false;
  77149. this._applyByPostProcess = false;
  77150. this._isEnabled = true;
  77151. /**
  77152. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  77153. */
  77154. this.onUpdateParameters = new BABYLON.Observable();
  77155. }
  77156. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  77157. /**
  77158. * Gets wether the color curves effect is enabled.
  77159. */
  77160. get: function () {
  77161. return this._colorCurvesEnabled;
  77162. },
  77163. /**
  77164. * Sets wether the color curves effect is enabled.
  77165. */
  77166. set: function (value) {
  77167. if (this._colorCurvesEnabled === value) {
  77168. return;
  77169. }
  77170. this._colorCurvesEnabled = value;
  77171. this._updateParameters();
  77172. },
  77173. enumerable: true,
  77174. configurable: true
  77175. });
  77176. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  77177. /**
  77178. * Gets wether the color grading effect is enabled.
  77179. */
  77180. get: function () {
  77181. return this._colorGradingEnabled;
  77182. },
  77183. /**
  77184. * Sets wether the color grading effect is enabled.
  77185. */
  77186. set: function (value) {
  77187. if (this._colorGradingEnabled === value) {
  77188. return;
  77189. }
  77190. this._colorGradingEnabled = value;
  77191. this._updateParameters();
  77192. },
  77193. enumerable: true,
  77194. configurable: true
  77195. });
  77196. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  77197. /**
  77198. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  77199. */
  77200. get: function () {
  77201. return this._colorGradingWithGreenDepth;
  77202. },
  77203. /**
  77204. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  77205. */
  77206. set: function (value) {
  77207. if (this._colorGradingWithGreenDepth === value) {
  77208. return;
  77209. }
  77210. this._colorGradingWithGreenDepth = value;
  77211. this._updateParameters();
  77212. },
  77213. enumerable: true,
  77214. configurable: true
  77215. });
  77216. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77217. /**
  77218. * Gets wether the color grading texture contains BGR values.
  77219. */
  77220. get: function () {
  77221. return this._colorGradingBGR;
  77222. },
  77223. /**
  77224. * Sets wether the color grading texture contains BGR values.
  77225. */
  77226. set: function (value) {
  77227. if (this._colorGradingBGR === value) {
  77228. return;
  77229. }
  77230. this._colorGradingBGR = value;
  77231. this._updateParameters();
  77232. },
  77233. enumerable: true,
  77234. configurable: true
  77235. });
  77236. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77237. /**
  77238. * Gets the Exposure used in the effect.
  77239. */
  77240. get: function () {
  77241. return this._exposure;
  77242. },
  77243. /**
  77244. * Sets the Exposure used in the effect.
  77245. */
  77246. set: function (value) {
  77247. if (this._exposure === value) {
  77248. return;
  77249. }
  77250. this._exposure = value;
  77251. this._updateParameters();
  77252. },
  77253. enumerable: true,
  77254. configurable: true
  77255. });
  77256. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77257. /**
  77258. * Gets wether the tone mapping effect is enabled.
  77259. */
  77260. get: function () {
  77261. return this._toneMappingEnabled;
  77262. },
  77263. /**
  77264. * Sets wether the tone mapping effect is enabled.
  77265. */
  77266. set: function (value) {
  77267. if (this._toneMappingEnabled === value) {
  77268. return;
  77269. }
  77270. this._toneMappingEnabled = value;
  77271. this._updateParameters();
  77272. },
  77273. enumerable: true,
  77274. configurable: true
  77275. });
  77276. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77277. /**
  77278. * Gets the contrast used in the effect.
  77279. */
  77280. get: function () {
  77281. return this._contrast;
  77282. },
  77283. /**
  77284. * Sets the contrast used in the effect.
  77285. */
  77286. set: function (value) {
  77287. if (this._contrast === value) {
  77288. return;
  77289. }
  77290. this._contrast = value;
  77291. this._updateParameters();
  77292. },
  77293. enumerable: true,
  77294. configurable: true
  77295. });
  77296. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77297. /**
  77298. * Gets the vignette blend mode allowing different kind of effect.
  77299. */
  77300. get: function () {
  77301. return this._vignetteBlendMode;
  77302. },
  77303. /**
  77304. * Sets the vignette blend mode allowing different kind of effect.
  77305. */
  77306. set: function (value) {
  77307. if (this._vignetteBlendMode === value) {
  77308. return;
  77309. }
  77310. this._vignetteBlendMode = value;
  77311. this._updateParameters();
  77312. },
  77313. enumerable: true,
  77314. configurable: true
  77315. });
  77316. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77317. /**
  77318. * Gets wether the vignette effect is enabled.
  77319. */
  77320. get: function () {
  77321. return this._vignetteEnabled;
  77322. },
  77323. /**
  77324. * Sets wether the vignette effect is enabled.
  77325. */
  77326. set: function (value) {
  77327. if (this._vignetteEnabled === value) {
  77328. return;
  77329. }
  77330. this._vignetteEnabled = value;
  77331. this._updateParameters();
  77332. },
  77333. enumerable: true,
  77334. configurable: true
  77335. });
  77336. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77337. /**
  77338. * Gets wether the image processing is applied through a post process or not.
  77339. */
  77340. get: function () {
  77341. return this._applyByPostProcess;
  77342. },
  77343. /**
  77344. * Sets wether the image processing is applied through a post process or not.
  77345. */
  77346. set: function (value) {
  77347. if (this._applyByPostProcess === value) {
  77348. return;
  77349. }
  77350. this._applyByPostProcess = value;
  77351. this._updateParameters();
  77352. },
  77353. enumerable: true,
  77354. configurable: true
  77355. });
  77356. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77357. /**
  77358. * Gets wether the image processing is enabled or not.
  77359. */
  77360. get: function () {
  77361. return this._isEnabled;
  77362. },
  77363. /**
  77364. * Sets wether the image processing is enabled or not.
  77365. */
  77366. set: function (value) {
  77367. if (this._isEnabled === value) {
  77368. return;
  77369. }
  77370. this._isEnabled = value;
  77371. this._updateParameters();
  77372. },
  77373. enumerable: true,
  77374. configurable: true
  77375. });
  77376. /**
  77377. * Method called each time the image processing information changes requires to recompile the effect.
  77378. */
  77379. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77380. this.onUpdateParameters.notifyObservers(this);
  77381. };
  77382. ImageProcessingConfiguration.prototype.getClassName = function () {
  77383. return "ImageProcessingConfiguration";
  77384. };
  77385. /**
  77386. * Prepare the list of uniforms associated with the Image Processing effects.
  77387. * @param uniformsList The list of uniforms used in the effect
  77388. * @param defines the list of defines currently in use
  77389. */
  77390. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77391. if (defines.EXPOSURE) {
  77392. uniforms.push("exposureLinear");
  77393. }
  77394. if (defines.CONTRAST) {
  77395. uniforms.push("contrast");
  77396. }
  77397. if (defines.COLORGRADING) {
  77398. uniforms.push("colorTransformSettings");
  77399. }
  77400. if (defines.VIGNETTE) {
  77401. uniforms.push("vInverseScreenSize");
  77402. uniforms.push("vignetteSettings1");
  77403. uniforms.push("vignetteSettings2");
  77404. }
  77405. if (defines.COLORCURVES) {
  77406. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77407. }
  77408. };
  77409. /**
  77410. * Prepare the list of samplers associated with the Image Processing effects.
  77411. * @param uniformsList The list of uniforms used in the effect
  77412. * @param defines the list of defines currently in use
  77413. */
  77414. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77415. if (defines.COLORGRADING) {
  77416. samplersList.push("txColorTransform");
  77417. }
  77418. };
  77419. /**
  77420. * Prepare the list of defines associated to the shader.
  77421. * @param defines the list of defines to complete
  77422. */
  77423. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77424. if (forPostProcess === void 0) { forPostProcess = false; }
  77425. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77426. defines.VIGNETTE = false;
  77427. defines.TONEMAPPING = false;
  77428. defines.CONTRAST = false;
  77429. defines.EXPOSURE = false;
  77430. defines.COLORCURVES = false;
  77431. defines.COLORGRADING = false;
  77432. defines.COLORGRADING3D = false;
  77433. defines.IMAGEPROCESSING = false;
  77434. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77435. return;
  77436. }
  77437. defines.VIGNETTE = this.vignetteEnabled;
  77438. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77439. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77440. defines.TONEMAPPING = this.toneMappingEnabled;
  77441. defines.CONTRAST = (this.contrast !== 1.0);
  77442. defines.EXPOSURE = (this.exposure !== 1.0);
  77443. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77444. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77445. if (defines.COLORGRADING) {
  77446. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77447. }
  77448. else {
  77449. defines.COLORGRADING3D = false;
  77450. }
  77451. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77452. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77453. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77454. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77455. };
  77456. /**
  77457. * Returns true if all the image processing information are ready.
  77458. */
  77459. ImageProcessingConfiguration.prototype.isReady = function () {
  77460. // Color Grading texure can not be none blocking.
  77461. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77462. };
  77463. /**
  77464. * Binds the image processing to the shader.
  77465. * @param effect The effect to bind to
  77466. */
  77467. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77468. if (aspectRatio === void 0) { aspectRatio = 1; }
  77469. // Color Curves
  77470. if (this._colorCurvesEnabled && this.colorCurves) {
  77471. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77472. }
  77473. // Vignette
  77474. if (this._vignetteEnabled) {
  77475. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77476. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77477. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77478. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77479. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77480. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77481. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77482. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77483. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77484. var vignettePower = -2.0 * this.vignetteWeight;
  77485. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77486. }
  77487. // Exposure
  77488. effect.setFloat("exposureLinear", this.exposure);
  77489. // Contrast
  77490. effect.setFloat("contrast", this.contrast);
  77491. // Color transform settings
  77492. if (this.colorGradingTexture) {
  77493. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77494. var textureSize = this.colorGradingTexture.getSize().height;
  77495. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77496. 0.5 / textureSize, // textureOffset
  77497. textureSize, // textureSize
  77498. this.colorGradingTexture.level // weight
  77499. );
  77500. }
  77501. };
  77502. /**
  77503. * Clones the current image processing instance.
  77504. * @return The cloned image processing
  77505. */
  77506. ImageProcessingConfiguration.prototype.clone = function () {
  77507. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77508. };
  77509. /**
  77510. * Serializes the current image processing instance to a json representation.
  77511. * @return a JSON representation
  77512. */
  77513. ImageProcessingConfiguration.prototype.serialize = function () {
  77514. return BABYLON.SerializationHelper.Serialize(this);
  77515. };
  77516. /**
  77517. * Parses the image processing from a json representation.
  77518. * @param source the JSON source to parse
  77519. * @return The parsed image processing
  77520. */
  77521. ImageProcessingConfiguration.Parse = function (source) {
  77522. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77523. };
  77524. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77525. /**
  77526. * Used to apply the vignette as a mix with the pixel color.
  77527. */
  77528. get: function () {
  77529. return this._VIGNETTEMODE_MULTIPLY;
  77530. },
  77531. enumerable: true,
  77532. configurable: true
  77533. });
  77534. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77535. /**
  77536. * Used to apply the vignette as a replacement of the pixel color.
  77537. */
  77538. get: function () {
  77539. return this._VIGNETTEMODE_OPAQUE;
  77540. },
  77541. enumerable: true,
  77542. configurable: true
  77543. });
  77544. // Static constants associated to the image processing.
  77545. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77546. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77547. __decorate([
  77548. BABYLON.serializeAsColorCurves()
  77549. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77550. __decorate([
  77551. BABYLON.serialize()
  77552. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77553. __decorate([
  77554. BABYLON.serializeAsTexture()
  77555. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77556. __decorate([
  77557. BABYLON.serialize()
  77558. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77559. __decorate([
  77560. BABYLON.serialize()
  77561. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77562. __decorate([
  77563. BABYLON.serialize()
  77564. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77565. __decorate([
  77566. BABYLON.serialize()
  77567. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77568. __decorate([
  77569. BABYLON.serialize()
  77570. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77571. __decorate([
  77572. BABYLON.serialize()
  77573. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77574. __decorate([
  77575. BABYLON.serialize()
  77576. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77577. __decorate([
  77578. BABYLON.serialize()
  77579. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77580. __decorate([
  77581. BABYLON.serialize()
  77582. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77583. __decorate([
  77584. BABYLON.serialize()
  77585. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77586. __decorate([
  77587. BABYLON.serializeAsColor4()
  77588. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77589. __decorate([
  77590. BABYLON.serialize()
  77591. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77592. __decorate([
  77593. BABYLON.serialize()
  77594. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77595. __decorate([
  77596. BABYLON.serialize()
  77597. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77598. __decorate([
  77599. BABYLON.serialize()
  77600. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77601. __decorate([
  77602. BABYLON.serialize()
  77603. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77604. return ImageProcessingConfiguration;
  77605. }());
  77606. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77607. })(BABYLON || (BABYLON = {}));
  77608. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77609. var BABYLON;
  77610. (function (BABYLON) {
  77611. /**
  77612. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77613. * It can help converting any input color in a desired output one. This can then be used to create effects
  77614. * from sepia, black and white to sixties or futuristic rendering...
  77615. *
  77616. * The only supported format is currently 3dl.
  77617. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77618. */
  77619. var ColorGradingTexture = /** @class */ (function (_super) {
  77620. __extends(ColorGradingTexture, _super);
  77621. /**
  77622. * Instantiates a ColorGradingTexture from the following parameters.
  77623. *
  77624. * @param url The location of the color gradind data (currently only supporting 3dl)
  77625. * @param scene The scene the texture will be used in
  77626. */
  77627. function ColorGradingTexture(url, scene) {
  77628. var _this = _super.call(this, scene) || this;
  77629. if (!url) {
  77630. return _this;
  77631. }
  77632. _this._engine = scene.getEngine();
  77633. _this._textureMatrix = BABYLON.Matrix.Identity();
  77634. _this.name = url;
  77635. _this.url = url;
  77636. _this.hasAlpha = false;
  77637. _this.isCube = false;
  77638. _this.is3D = _this._engine.webGLVersion > 1;
  77639. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77640. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77641. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77642. _this.anisotropicFilteringLevel = 1;
  77643. _this._texture = _this._getFromCache(url, true);
  77644. if (!_this._texture) {
  77645. if (!scene.useDelayedTextureLoading) {
  77646. _this.loadTexture();
  77647. }
  77648. else {
  77649. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77650. }
  77651. }
  77652. return _this;
  77653. }
  77654. /**
  77655. * Returns the texture matrix used in most of the material.
  77656. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77657. */
  77658. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77659. return this._textureMatrix;
  77660. };
  77661. /**
  77662. * Occurs when the file being loaded is a .3dl LUT file.
  77663. */
  77664. ColorGradingTexture.prototype.load3dlTexture = function () {
  77665. var engine = this._engine;
  77666. var texture;
  77667. if (engine.webGLVersion === 1) {
  77668. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77669. }
  77670. else {
  77671. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77672. }
  77673. this._texture = texture;
  77674. var callback = function (text) {
  77675. if (typeof text !== "string") {
  77676. return;
  77677. }
  77678. var data = null;
  77679. var tempData = null;
  77680. var line;
  77681. var lines = text.split('\n');
  77682. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77683. var maxColor = 0;
  77684. for (var i = 0; i < lines.length; i++) {
  77685. line = lines[i];
  77686. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77687. continue;
  77688. if (line.indexOf('#') === 0)
  77689. continue;
  77690. var words = line.split(" ");
  77691. if (size === 0) {
  77692. // Number of space + one
  77693. size = words.length;
  77694. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77695. tempData = new Float32Array(size * size * size * 4);
  77696. continue;
  77697. }
  77698. if (size != 0) {
  77699. var r = Math.max(parseInt(words[0]), 0);
  77700. var g = Math.max(parseInt(words[1]), 0);
  77701. var b = Math.max(parseInt(words[2]), 0);
  77702. maxColor = Math.max(r, maxColor);
  77703. maxColor = Math.max(g, maxColor);
  77704. maxColor = Math.max(b, maxColor);
  77705. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77706. if (tempData) {
  77707. tempData[pixelStorageIndex + 0] = r;
  77708. tempData[pixelStorageIndex + 1] = g;
  77709. tempData[pixelStorageIndex + 2] = b;
  77710. }
  77711. pixelIndexSlice++;
  77712. if (pixelIndexSlice % size == 0) {
  77713. pixelIndexH++;
  77714. pixelIndexSlice = 0;
  77715. if (pixelIndexH % size == 0) {
  77716. pixelIndexW++;
  77717. pixelIndexH = 0;
  77718. }
  77719. }
  77720. }
  77721. }
  77722. if (tempData && data) {
  77723. for (var i = 0; i < tempData.length; i++) {
  77724. if (i > 0 && (i + 1) % 4 === 0) {
  77725. data[i] = 255;
  77726. }
  77727. else {
  77728. var value = tempData[i];
  77729. data[i] = (value / maxColor * 255);
  77730. }
  77731. }
  77732. }
  77733. if (texture.is3D) {
  77734. texture.updateSize(size, size, size);
  77735. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77736. }
  77737. else {
  77738. texture.updateSize(size * size, size);
  77739. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77740. }
  77741. };
  77742. var scene = this.getScene();
  77743. if (scene) {
  77744. scene._loadFile(this.url, callback);
  77745. }
  77746. else {
  77747. this._engine._loadFile(this.url, callback);
  77748. }
  77749. return this._texture;
  77750. };
  77751. /**
  77752. * Starts the loading process of the texture.
  77753. */
  77754. ColorGradingTexture.prototype.loadTexture = function () {
  77755. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77756. this.load3dlTexture();
  77757. }
  77758. };
  77759. /**
  77760. * Clones the color gradind texture.
  77761. */
  77762. ColorGradingTexture.prototype.clone = function () {
  77763. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77764. // Base texture
  77765. newTexture.level = this.level;
  77766. return newTexture;
  77767. };
  77768. /**
  77769. * Called during delayed load for textures.
  77770. */
  77771. ColorGradingTexture.prototype.delayLoad = function () {
  77772. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77773. return;
  77774. }
  77775. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77776. this._texture = this._getFromCache(this.url, true);
  77777. if (!this._texture) {
  77778. this.loadTexture();
  77779. }
  77780. };
  77781. /**
  77782. * Parses a color grading texture serialized by Babylon.
  77783. * @param parsedTexture The texture information being parsedTexture
  77784. * @param scene The scene to load the texture in
  77785. * @param rootUrl The root url of the data assets to load
  77786. * @return A color gradind texture
  77787. */
  77788. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77789. var texture = null;
  77790. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77791. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77792. texture.name = parsedTexture.name;
  77793. texture.level = parsedTexture.level;
  77794. }
  77795. return texture;
  77796. };
  77797. /**
  77798. * Serializes the LUT texture to json format.
  77799. */
  77800. ColorGradingTexture.prototype.serialize = function () {
  77801. if (!this.name) {
  77802. return null;
  77803. }
  77804. var serializationObject = {};
  77805. serializationObject.name = this.name;
  77806. serializationObject.level = this.level;
  77807. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77808. return serializationObject;
  77809. };
  77810. /**
  77811. * Empty line regex stored for GC.
  77812. */
  77813. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77814. return ColorGradingTexture;
  77815. }(BABYLON.BaseTexture));
  77816. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77817. })(BABYLON || (BABYLON = {}));
  77818. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77819. var BABYLON;
  77820. (function (BABYLON) {
  77821. /**
  77822. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77823. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77824. * 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;
  77825. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77826. */
  77827. var ColorCurves = /** @class */ (function () {
  77828. function ColorCurves() {
  77829. this._dirty = true;
  77830. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77831. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77832. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77833. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77834. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77835. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77836. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77837. this._globalHue = 30;
  77838. this._globalDensity = 0;
  77839. this._globalSaturation = 0;
  77840. this._globalExposure = 0;
  77841. this._highlightsHue = 30;
  77842. this._highlightsDensity = 0;
  77843. this._highlightsSaturation = 0;
  77844. this._highlightsExposure = 0;
  77845. this._midtonesHue = 30;
  77846. this._midtonesDensity = 0;
  77847. this._midtonesSaturation = 0;
  77848. this._midtonesExposure = 0;
  77849. this._shadowsHue = 30;
  77850. this._shadowsDensity = 0;
  77851. this._shadowsSaturation = 0;
  77852. this._shadowsExposure = 0;
  77853. }
  77854. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77855. /**
  77856. * Gets the global Hue value.
  77857. * 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).
  77858. */
  77859. get: function () {
  77860. return this._globalHue;
  77861. },
  77862. /**
  77863. * Sets the global Hue value.
  77864. * 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).
  77865. */
  77866. set: function (value) {
  77867. this._globalHue = value;
  77868. this._dirty = true;
  77869. },
  77870. enumerable: true,
  77871. configurable: true
  77872. });
  77873. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77874. /**
  77875. * Gets the global Density value.
  77876. * 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.
  77877. * Values less than zero provide a filter of opposite hue.
  77878. */
  77879. get: function () {
  77880. return this._globalDensity;
  77881. },
  77882. /**
  77883. * Sets the global Density value.
  77884. * 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.
  77885. * Values less than zero provide a filter of opposite hue.
  77886. */
  77887. set: function (value) {
  77888. this._globalDensity = value;
  77889. this._dirty = true;
  77890. },
  77891. enumerable: true,
  77892. configurable: true
  77893. });
  77894. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77895. /**
  77896. * Gets the global Saturation value.
  77897. * 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.
  77898. */
  77899. get: function () {
  77900. return this._globalSaturation;
  77901. },
  77902. /**
  77903. * Sets the global Saturation value.
  77904. * 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.
  77905. */
  77906. set: function (value) {
  77907. this._globalSaturation = value;
  77908. this._dirty = true;
  77909. },
  77910. enumerable: true,
  77911. configurable: true
  77912. });
  77913. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77914. /**
  77915. * Gets the global Exposure value.
  77916. * 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.
  77917. */
  77918. get: function () {
  77919. return this._globalExposure;
  77920. },
  77921. /**
  77922. * Sets the global Exposure value.
  77923. * 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.
  77924. */
  77925. set: function (value) {
  77926. this._globalExposure = value;
  77927. this._dirty = true;
  77928. },
  77929. enumerable: true,
  77930. configurable: true
  77931. });
  77932. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77933. /**
  77934. * Gets the highlights Hue value.
  77935. * 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).
  77936. */
  77937. get: function () {
  77938. return this._highlightsHue;
  77939. },
  77940. /**
  77941. * Sets the highlights Hue value.
  77942. * 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).
  77943. */
  77944. set: function (value) {
  77945. this._highlightsHue = value;
  77946. this._dirty = true;
  77947. },
  77948. enumerable: true,
  77949. configurable: true
  77950. });
  77951. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77952. /**
  77953. * Gets the highlights Density value.
  77954. * 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.
  77955. * Values less than zero provide a filter of opposite hue.
  77956. */
  77957. get: function () {
  77958. return this._highlightsDensity;
  77959. },
  77960. /**
  77961. * Sets the highlights Density value.
  77962. * 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.
  77963. * Values less than zero provide a filter of opposite hue.
  77964. */
  77965. set: function (value) {
  77966. this._highlightsDensity = value;
  77967. this._dirty = true;
  77968. },
  77969. enumerable: true,
  77970. configurable: true
  77971. });
  77972. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77973. /**
  77974. * Gets the highlights Saturation value.
  77975. * 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.
  77976. */
  77977. get: function () {
  77978. return this._highlightsSaturation;
  77979. },
  77980. /**
  77981. * Sets the highlights Saturation value.
  77982. * 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.
  77983. */
  77984. set: function (value) {
  77985. this._highlightsSaturation = value;
  77986. this._dirty = true;
  77987. },
  77988. enumerable: true,
  77989. configurable: true
  77990. });
  77991. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  77992. /**
  77993. * Gets the highlights Exposure value.
  77994. * 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.
  77995. */
  77996. get: function () {
  77997. return this._highlightsExposure;
  77998. },
  77999. /**
  78000. * Sets the highlights Exposure value.
  78001. * 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.
  78002. */
  78003. set: function (value) {
  78004. this._highlightsExposure = value;
  78005. this._dirty = true;
  78006. },
  78007. enumerable: true,
  78008. configurable: true
  78009. });
  78010. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  78011. /**
  78012. * Gets the midtones Hue value.
  78013. * 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).
  78014. */
  78015. get: function () {
  78016. return this._midtonesHue;
  78017. },
  78018. /**
  78019. * Sets the midtones Hue value.
  78020. * 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).
  78021. */
  78022. set: function (value) {
  78023. this._midtonesHue = value;
  78024. this._dirty = true;
  78025. },
  78026. enumerable: true,
  78027. configurable: true
  78028. });
  78029. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  78030. /**
  78031. * Gets the midtones Density value.
  78032. * 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.
  78033. * Values less than zero provide a filter of opposite hue.
  78034. */
  78035. get: function () {
  78036. return this._midtonesDensity;
  78037. },
  78038. /**
  78039. * Sets the midtones Density value.
  78040. * 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.
  78041. * Values less than zero provide a filter of opposite hue.
  78042. */
  78043. set: function (value) {
  78044. this._midtonesDensity = value;
  78045. this._dirty = true;
  78046. },
  78047. enumerable: true,
  78048. configurable: true
  78049. });
  78050. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  78051. /**
  78052. * Gets the midtones Saturation value.
  78053. * 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.
  78054. */
  78055. get: function () {
  78056. return this._midtonesSaturation;
  78057. },
  78058. /**
  78059. * Sets the midtones Saturation value.
  78060. * 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.
  78061. */
  78062. set: function (value) {
  78063. this._midtonesSaturation = value;
  78064. this._dirty = true;
  78065. },
  78066. enumerable: true,
  78067. configurable: true
  78068. });
  78069. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  78070. /**
  78071. * Gets the midtones Exposure value.
  78072. * 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.
  78073. */
  78074. get: function () {
  78075. return this._midtonesExposure;
  78076. },
  78077. /**
  78078. * Sets the midtones Exposure value.
  78079. * 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.
  78080. */
  78081. set: function (value) {
  78082. this._midtonesExposure = value;
  78083. this._dirty = true;
  78084. },
  78085. enumerable: true,
  78086. configurable: true
  78087. });
  78088. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  78089. /**
  78090. * Gets the shadows Hue value.
  78091. * 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).
  78092. */
  78093. get: function () {
  78094. return this._shadowsHue;
  78095. },
  78096. /**
  78097. * Sets the shadows Hue value.
  78098. * 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).
  78099. */
  78100. set: function (value) {
  78101. this._shadowsHue = value;
  78102. this._dirty = true;
  78103. },
  78104. enumerable: true,
  78105. configurable: true
  78106. });
  78107. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  78108. /**
  78109. * Gets the shadows Density value.
  78110. * 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.
  78111. * Values less than zero provide a filter of opposite hue.
  78112. */
  78113. get: function () {
  78114. return this._shadowsDensity;
  78115. },
  78116. /**
  78117. * Sets the shadows Density value.
  78118. * 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.
  78119. * Values less than zero provide a filter of opposite hue.
  78120. */
  78121. set: function (value) {
  78122. this._shadowsDensity = value;
  78123. this._dirty = true;
  78124. },
  78125. enumerable: true,
  78126. configurable: true
  78127. });
  78128. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  78129. /**
  78130. * Gets the shadows Saturation value.
  78131. * 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.
  78132. */
  78133. get: function () {
  78134. return this._shadowsSaturation;
  78135. },
  78136. /**
  78137. * Sets the shadows Saturation value.
  78138. * 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.
  78139. */
  78140. set: function (value) {
  78141. this._shadowsSaturation = value;
  78142. this._dirty = true;
  78143. },
  78144. enumerable: true,
  78145. configurable: true
  78146. });
  78147. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  78148. /**
  78149. * Gets the shadows Exposure value.
  78150. * 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.
  78151. */
  78152. get: function () {
  78153. return this._shadowsExposure;
  78154. },
  78155. /**
  78156. * Sets the shadows Exposure value.
  78157. * 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.
  78158. */
  78159. set: function (value) {
  78160. this._shadowsExposure = value;
  78161. this._dirty = true;
  78162. },
  78163. enumerable: true,
  78164. configurable: true
  78165. });
  78166. ColorCurves.prototype.getClassName = function () {
  78167. return "ColorCurves";
  78168. };
  78169. /**
  78170. * Binds the color curves to the shader.
  78171. * @param colorCurves The color curve to bind
  78172. * @param effect The effect to bind to
  78173. */
  78174. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  78175. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  78176. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  78177. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  78178. if (colorCurves._dirty) {
  78179. colorCurves._dirty = false;
  78180. // Fill in global info.
  78181. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  78182. // Compute highlights info.
  78183. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  78184. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  78185. // Compute midtones info.
  78186. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  78187. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  78188. // Compute shadows info.
  78189. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  78190. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  78191. // Compute deltas (neutral is midtones).
  78192. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  78193. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  78194. }
  78195. if (effect) {
  78196. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  78197. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  78198. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  78199. }
  78200. };
  78201. /**
  78202. * Prepare the list of uniforms associated with the ColorCurves effects.
  78203. * @param uniformsList The list of uniforms used in the effect
  78204. */
  78205. ColorCurves.PrepareUniforms = function (uniformsList) {
  78206. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  78207. };
  78208. /**
  78209. * Returns color grading data based on a hue, density, saturation and exposure value.
  78210. * @param filterHue The hue of the color filter.
  78211. * @param filterDensity The density of the color filter.
  78212. * @param saturation The saturation.
  78213. * @param exposure The exposure.
  78214. * @param result The result data container.
  78215. */
  78216. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78217. if (hue == null) {
  78218. return;
  78219. }
  78220. hue = ColorCurves.clamp(hue, 0, 360);
  78221. density = ColorCurves.clamp(density, -100, 100);
  78222. saturation = ColorCurves.clamp(saturation, -100, 100);
  78223. exposure = ColorCurves.clamp(exposure, -100, 100);
  78224. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78225. // so that the maximum filter density is only 50% control. This provides fine control
  78226. // for small values and reasonable range.
  78227. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78228. density *= 0.5;
  78229. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78230. if (density < 0) {
  78231. density *= -1;
  78232. hue = (hue + 180) % 360;
  78233. }
  78234. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78235. result.scaleToRef(2, result);
  78236. result.a = 1 + 0.01 * saturation;
  78237. };
  78238. /**
  78239. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78240. * @param value The input slider value in range [-100,100].
  78241. * @returns Adjusted value.
  78242. */
  78243. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78244. value /= 100;
  78245. var x = Math.abs(value);
  78246. x = Math.pow(x, 2);
  78247. if (value < 0) {
  78248. x *= -1;
  78249. }
  78250. x *= 100;
  78251. return x;
  78252. };
  78253. /**
  78254. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78255. * @param hue The hue (H) input.
  78256. * @param saturation The saturation (S) input.
  78257. * @param brightness The brightness (B) input.
  78258. * @result An RGBA color represented as Vector4.
  78259. */
  78260. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78261. var h = ColorCurves.clamp(hue, 0, 360);
  78262. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78263. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78264. if (s === 0) {
  78265. result.r = v;
  78266. result.g = v;
  78267. result.b = v;
  78268. }
  78269. else {
  78270. // sector 0 to 5
  78271. h /= 60;
  78272. var i = Math.floor(h);
  78273. // fractional part of h
  78274. var f = h - i;
  78275. var p = v * (1 - s);
  78276. var q = v * (1 - s * f);
  78277. var t = v * (1 - s * (1 - f));
  78278. switch (i) {
  78279. case 0:
  78280. result.r = v;
  78281. result.g = t;
  78282. result.b = p;
  78283. break;
  78284. case 1:
  78285. result.r = q;
  78286. result.g = v;
  78287. result.b = p;
  78288. break;
  78289. case 2:
  78290. result.r = p;
  78291. result.g = v;
  78292. result.b = t;
  78293. break;
  78294. case 3:
  78295. result.r = p;
  78296. result.g = q;
  78297. result.b = v;
  78298. break;
  78299. case 4:
  78300. result.r = t;
  78301. result.g = p;
  78302. result.b = v;
  78303. break;
  78304. default: // case 5:
  78305. result.r = v;
  78306. result.g = p;
  78307. result.b = q;
  78308. break;
  78309. }
  78310. }
  78311. result.a = 1;
  78312. };
  78313. /**
  78314. * Returns a value clamped between min and max
  78315. * @param value The value to clamp
  78316. * @param min The minimum of value
  78317. * @param max The maximum of value
  78318. * @returns The clamped value.
  78319. */
  78320. ColorCurves.clamp = function (value, min, max) {
  78321. return Math.min(Math.max(value, min), max);
  78322. };
  78323. /**
  78324. * Clones the current color curve instance.
  78325. * @return The cloned curves
  78326. */
  78327. ColorCurves.prototype.clone = function () {
  78328. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78329. };
  78330. /**
  78331. * Serializes the current color curve instance to a json representation.
  78332. * @return a JSON representation
  78333. */
  78334. ColorCurves.prototype.serialize = function () {
  78335. return BABYLON.SerializationHelper.Serialize(this);
  78336. };
  78337. /**
  78338. * Parses the color curve from a json representation.
  78339. * @param source the JSON source to parse
  78340. * @return The parsed curves
  78341. */
  78342. ColorCurves.Parse = function (source) {
  78343. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78344. };
  78345. __decorate([
  78346. BABYLON.serialize()
  78347. ], ColorCurves.prototype, "_globalHue", void 0);
  78348. __decorate([
  78349. BABYLON.serialize()
  78350. ], ColorCurves.prototype, "_globalDensity", void 0);
  78351. __decorate([
  78352. BABYLON.serialize()
  78353. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78354. __decorate([
  78355. BABYLON.serialize()
  78356. ], ColorCurves.prototype, "_globalExposure", void 0);
  78357. __decorate([
  78358. BABYLON.serialize()
  78359. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78360. __decorate([
  78361. BABYLON.serialize()
  78362. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78363. __decorate([
  78364. BABYLON.serialize()
  78365. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78366. __decorate([
  78367. BABYLON.serialize()
  78368. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78369. __decorate([
  78370. BABYLON.serialize()
  78371. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78372. __decorate([
  78373. BABYLON.serialize()
  78374. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78375. __decorate([
  78376. BABYLON.serialize()
  78377. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78378. __decorate([
  78379. BABYLON.serialize()
  78380. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78381. return ColorCurves;
  78382. }());
  78383. BABYLON.ColorCurves = ColorCurves;
  78384. })(BABYLON || (BABYLON = {}));
  78385. //# sourceMappingURL=babylon.colorCurves.js.map
  78386. var BABYLON;
  78387. (function (BABYLON) {
  78388. var RefractionPostProcess = /** @class */ (function (_super) {
  78389. __extends(RefractionPostProcess, _super);
  78390. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78391. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78392. _this.color = color;
  78393. _this.depth = depth;
  78394. _this.colorLevel = colorLevel;
  78395. _this._ownRefractionTexture = true;
  78396. _this.onActivateObservable.add(function (cam) {
  78397. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78398. });
  78399. _this.onApplyObservable.add(function (effect) {
  78400. effect.setColor3("baseColor", _this.color);
  78401. effect.setFloat("depth", _this.depth);
  78402. effect.setFloat("colorLevel", _this.colorLevel);
  78403. effect.setTexture("refractionSampler", _this._refTexture);
  78404. });
  78405. return _this;
  78406. }
  78407. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78408. /**
  78409. * Gets or sets the refraction texture
  78410. * Please note that you are responsible for disposing the texture if you set it manually
  78411. */
  78412. get: function () {
  78413. return this._refTexture;
  78414. },
  78415. set: function (value) {
  78416. if (this._refTexture && this._ownRefractionTexture) {
  78417. this._refTexture.dispose();
  78418. }
  78419. this._refTexture = value;
  78420. this._ownRefractionTexture = false;
  78421. },
  78422. enumerable: true,
  78423. configurable: true
  78424. });
  78425. // Methods
  78426. RefractionPostProcess.prototype.dispose = function (camera) {
  78427. if (this._refTexture && this._ownRefractionTexture) {
  78428. this._refTexture.dispose();
  78429. this._refTexture = null;
  78430. }
  78431. _super.prototype.dispose.call(this, camera);
  78432. };
  78433. return RefractionPostProcess;
  78434. }(BABYLON.PostProcess));
  78435. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78436. })(BABYLON || (BABYLON = {}));
  78437. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78438. var BABYLON;
  78439. (function (BABYLON) {
  78440. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78441. __extends(BlackAndWhitePostProcess, _super);
  78442. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78443. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78444. _this.degree = 1;
  78445. _this.onApplyObservable.add(function (effect) {
  78446. effect.setFloat("degree", _this.degree);
  78447. });
  78448. return _this;
  78449. }
  78450. return BlackAndWhitePostProcess;
  78451. }(BABYLON.PostProcess));
  78452. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78453. })(BABYLON || (BABYLON = {}));
  78454. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78455. var BABYLON;
  78456. (function (BABYLON) {
  78457. /**
  78458. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78459. * input texture to perform effects such as edge detection or sharpening
  78460. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78461. */
  78462. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78463. __extends(ConvolutionPostProcess, _super);
  78464. /**
  78465. * Creates a new instance ConvolutionPostProcess
  78466. * @param name The name of the effect.
  78467. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78468. * @param options The required width/height ratio to downsize to before computing the render pass.
  78469. * @param camera The camera to apply the render pass to.
  78470. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78471. * @param engine The engine which the post process will be applied. (default: current engine)
  78472. * @param reusable If the post process can be reused on the same frame. (default: false)
  78473. * @param textureType Type of textures used when performing the post process. (default: 0)
  78474. */
  78475. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78476. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78477. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78478. _this.kernel = kernel;
  78479. _this.onApply = function (effect) {
  78480. effect.setFloat2("screenSize", _this.width, _this.height);
  78481. effect.setArray("kernel", _this.kernel);
  78482. };
  78483. return _this;
  78484. }
  78485. // Statics
  78486. /**
  78487. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78488. */
  78489. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78490. /**
  78491. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78492. */
  78493. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78494. /**
  78495. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78496. */
  78497. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78498. /**
  78499. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78500. */
  78501. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78502. /**
  78503. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78504. */
  78505. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78506. /**
  78507. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78508. */
  78509. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78510. return ConvolutionPostProcess;
  78511. }(BABYLON.PostProcess));
  78512. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78513. })(BABYLON || (BABYLON = {}));
  78514. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78515. var BABYLON;
  78516. (function (BABYLON) {
  78517. var FilterPostProcess = /** @class */ (function (_super) {
  78518. __extends(FilterPostProcess, _super);
  78519. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78520. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78521. _this.kernelMatrix = kernelMatrix;
  78522. _this.onApply = function (effect) {
  78523. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78524. };
  78525. return _this;
  78526. }
  78527. return FilterPostProcess;
  78528. }(BABYLON.PostProcess));
  78529. BABYLON.FilterPostProcess = FilterPostProcess;
  78530. })(BABYLON || (BABYLON = {}));
  78531. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78532. var BABYLON;
  78533. (function (BABYLON) {
  78534. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78535. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78536. __extends(VolumetricLightScatteringPostProcess, _super);
  78537. /**
  78538. * @constructor
  78539. * @param {string} name - The post-process name
  78540. * @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)
  78541. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78542. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78543. * @param {number} samples - The post-process quality, default 100
  78544. * @param {number} samplingMode - The post-process filtering mode
  78545. * @param {BABYLON.Engine} engine - The babylon engine
  78546. * @param {boolean} reusable - If the post-process is reusable
  78547. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78548. */
  78549. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78550. if (samples === void 0) { samples = 100; }
  78551. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78552. 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;
  78553. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78554. /**
  78555. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78556. */
  78557. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78558. /**
  78559. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78560. */
  78561. _this.useCustomMeshPosition = false;
  78562. /**
  78563. * If the post-process should inverse the light scattering direction
  78564. */
  78565. _this.invert = true;
  78566. /**
  78567. * Array containing the excluded meshes not rendered in the internal pass
  78568. */
  78569. _this.excludedMeshes = new Array();
  78570. /**
  78571. * Controls the overall intensity of the post-process
  78572. */
  78573. _this.exposure = 0.3;
  78574. /**
  78575. * Dissipates each sample's contribution in range [0, 1]
  78576. */
  78577. _this.decay = 0.96815;
  78578. /**
  78579. * Controls the overall intensity of each sample
  78580. */
  78581. _this.weight = 0.58767;
  78582. /**
  78583. * Controls the density of each sample
  78584. */
  78585. _this.density = 0.926;
  78586. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78587. engine = scene.getEngine();
  78588. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78589. // Configure mesh
  78590. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78591. // Configure
  78592. _this._createPass(scene, ratio.passRatio || ratio);
  78593. _this.onActivate = function (camera) {
  78594. if (!_this.isSupported) {
  78595. _this.dispose(camera);
  78596. }
  78597. _this.onActivate = null;
  78598. };
  78599. _this.onApplyObservable.add(function (effect) {
  78600. _this._updateMeshScreenCoordinates(scene);
  78601. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78602. effect.setFloat("exposure", _this.exposure);
  78603. effect.setFloat("decay", _this.decay);
  78604. effect.setFloat("weight", _this.weight);
  78605. effect.setFloat("density", _this.density);
  78606. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78607. });
  78608. return _this;
  78609. }
  78610. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78611. get: function () {
  78612. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78613. return false;
  78614. },
  78615. set: function (useDiffuseColor) {
  78616. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78617. },
  78618. enumerable: true,
  78619. configurable: true
  78620. });
  78621. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78622. return "VolumetricLightScatteringPostProcess";
  78623. };
  78624. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78625. var mesh = subMesh.getMesh();
  78626. // Render this.mesh as default
  78627. if (mesh === this.mesh && mesh.material) {
  78628. return mesh.material.isReady(mesh);
  78629. }
  78630. var defines = [];
  78631. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78632. var material = subMesh.getMaterial();
  78633. // Alpha test
  78634. if (material) {
  78635. if (material.needAlphaTesting()) {
  78636. defines.push("#define ALPHATEST");
  78637. }
  78638. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78639. attribs.push(BABYLON.VertexBuffer.UVKind);
  78640. defines.push("#define UV1");
  78641. }
  78642. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78643. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78644. defines.push("#define UV2");
  78645. }
  78646. }
  78647. // Bones
  78648. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78649. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78650. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78651. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78652. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78653. }
  78654. else {
  78655. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78656. }
  78657. // Instances
  78658. if (useInstances) {
  78659. defines.push("#define INSTANCES");
  78660. attribs.push("world0");
  78661. attribs.push("world1");
  78662. attribs.push("world2");
  78663. attribs.push("world3");
  78664. }
  78665. // Get correct effect
  78666. var join = defines.join("\n");
  78667. if (this._cachedDefines !== join) {
  78668. this._cachedDefines = join;
  78669. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78670. }
  78671. return this._volumetricLightScatteringPass.isReady();
  78672. };
  78673. /**
  78674. * Sets the new light position for light scattering effect
  78675. * @param {BABYLON.Vector3} The new custom light position
  78676. */
  78677. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78678. this.customMeshPosition = position;
  78679. };
  78680. /**
  78681. * Returns the light position for light scattering effect
  78682. * @return {BABYLON.Vector3} The custom light position
  78683. */
  78684. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78685. return this.customMeshPosition;
  78686. };
  78687. /**
  78688. * Disposes the internal assets and detaches the post-process from the camera
  78689. */
  78690. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78691. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78692. if (rttIndex !== -1) {
  78693. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78694. }
  78695. this._volumetricLightScatteringRTT.dispose();
  78696. _super.prototype.dispose.call(this, camera);
  78697. };
  78698. /**
  78699. * Returns the render target texture used by the post-process
  78700. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78701. */
  78702. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78703. return this._volumetricLightScatteringRTT;
  78704. };
  78705. // Private methods
  78706. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78707. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78708. return true;
  78709. }
  78710. return false;
  78711. };
  78712. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78713. var _this = this;
  78714. var engine = scene.getEngine();
  78715. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78716. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78717. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78718. this._volumetricLightScatteringRTT.renderList = null;
  78719. this._volumetricLightScatteringRTT.renderParticles = false;
  78720. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78721. var camera = this.getCamera();
  78722. if (camera) {
  78723. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78724. }
  78725. else {
  78726. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78727. }
  78728. // Custom render function for submeshes
  78729. var renderSubMesh = function (subMesh) {
  78730. var mesh = subMesh.getRenderingMesh();
  78731. if (_this._meshExcluded(mesh)) {
  78732. return;
  78733. }
  78734. var material = subMesh.getMaterial();
  78735. if (!material) {
  78736. return;
  78737. }
  78738. var scene = mesh.getScene();
  78739. var engine = scene.getEngine();
  78740. // Culling
  78741. engine.setState(material.backFaceCulling);
  78742. // Managing instances
  78743. var batch = mesh._getInstancesRenderList(subMesh._id);
  78744. if (batch.mustReturn) {
  78745. return;
  78746. }
  78747. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78748. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78749. var effect = _this._volumetricLightScatteringPass;
  78750. if (mesh === _this.mesh) {
  78751. if (subMesh.effect) {
  78752. effect = subMesh.effect;
  78753. }
  78754. else {
  78755. effect = material.getEffect();
  78756. }
  78757. }
  78758. engine.enableEffect(effect);
  78759. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78760. if (mesh === _this.mesh) {
  78761. material.bind(mesh.getWorldMatrix(), mesh);
  78762. }
  78763. else {
  78764. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78765. // Alpha test
  78766. if (material && material.needAlphaTesting()) {
  78767. var alphaTexture = material.getAlphaTestTexture();
  78768. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78769. if (alphaTexture) {
  78770. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78771. }
  78772. }
  78773. // Bones
  78774. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78775. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78776. }
  78777. }
  78778. // Draw
  78779. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78780. }
  78781. };
  78782. // Render target texture callbacks
  78783. var savedSceneClearColor;
  78784. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78785. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78786. savedSceneClearColor = scene.clearColor;
  78787. scene.clearColor = sceneClearColor;
  78788. });
  78789. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78790. scene.clearColor = savedSceneClearColor;
  78791. });
  78792. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78793. var engine = scene.getEngine();
  78794. var index;
  78795. if (depthOnlySubMeshes.length) {
  78796. engine.setColorWrite(false);
  78797. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78798. renderSubMesh(depthOnlySubMeshes.data[index]);
  78799. }
  78800. engine.setColorWrite(true);
  78801. }
  78802. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78803. renderSubMesh(opaqueSubMeshes.data[index]);
  78804. }
  78805. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78806. renderSubMesh(alphaTestSubMeshes.data[index]);
  78807. }
  78808. if (transparentSubMeshes.length) {
  78809. // Sort sub meshes
  78810. for (index = 0; index < transparentSubMeshes.length; index++) {
  78811. var submesh = transparentSubMeshes.data[index];
  78812. var boundingInfo = submesh.getBoundingInfo();
  78813. if (boundingInfo && scene.activeCamera) {
  78814. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78815. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78816. }
  78817. }
  78818. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78819. sortedArray.sort(function (a, b) {
  78820. // Alpha index first
  78821. if (a._alphaIndex > b._alphaIndex) {
  78822. return 1;
  78823. }
  78824. if (a._alphaIndex < b._alphaIndex) {
  78825. return -1;
  78826. }
  78827. // Then distance to camera
  78828. if (a._distanceToCamera < b._distanceToCamera) {
  78829. return 1;
  78830. }
  78831. if (a._distanceToCamera > b._distanceToCamera) {
  78832. return -1;
  78833. }
  78834. return 0;
  78835. });
  78836. // Render sub meshes
  78837. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78838. for (index = 0; index < sortedArray.length; index++) {
  78839. renderSubMesh(sortedArray[index]);
  78840. }
  78841. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78842. }
  78843. };
  78844. };
  78845. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78846. var transform = scene.getTransformMatrix();
  78847. var meshPosition;
  78848. if (this.useCustomMeshPosition) {
  78849. meshPosition = this.customMeshPosition;
  78850. }
  78851. else if (this.attachedNode) {
  78852. meshPosition = this.attachedNode.position;
  78853. }
  78854. else {
  78855. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78856. }
  78857. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78858. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78859. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78860. if (this.invert)
  78861. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78862. };
  78863. // Static methods
  78864. /**
  78865. * Creates a default mesh for the Volumeric Light Scattering post-process
  78866. * @param {string} The mesh name
  78867. * @param {BABYLON.Scene} The scene where to create the mesh
  78868. * @return {BABYLON.Mesh} the default mesh
  78869. */
  78870. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78871. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78872. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78873. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78874. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78875. mesh.material = material;
  78876. return mesh;
  78877. };
  78878. __decorate([
  78879. BABYLON.serializeAsVector3()
  78880. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78881. __decorate([
  78882. BABYLON.serialize()
  78883. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78884. __decorate([
  78885. BABYLON.serialize()
  78886. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78887. __decorate([
  78888. BABYLON.serializeAsMeshReference()
  78889. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78890. __decorate([
  78891. BABYLON.serialize()
  78892. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78893. __decorate([
  78894. BABYLON.serialize()
  78895. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78896. __decorate([
  78897. BABYLON.serialize()
  78898. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78899. __decorate([
  78900. BABYLON.serialize()
  78901. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78902. __decorate([
  78903. BABYLON.serialize()
  78904. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78905. return VolumetricLightScatteringPostProcess;
  78906. }(BABYLON.PostProcess));
  78907. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78908. })(BABYLON || (BABYLON = {}));
  78909. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78910. //
  78911. // This post-process allows the modification of rendered colors by using
  78912. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78913. //
  78914. // The object needs to be provided an url to a texture containing the color
  78915. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78916. // Use an image editing software to tweak the LUT to match your needs.
  78917. //
  78918. // For an example of a color LUT, see here:
  78919. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78920. // For explanations on color grading, see here:
  78921. // http://udn.epicgames.com/Three/ColorGrading.html
  78922. //
  78923. var BABYLON;
  78924. (function (BABYLON) {
  78925. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78926. __extends(ColorCorrectionPostProcess, _super);
  78927. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78928. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78929. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78930. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78931. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78932. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78933. _this.onApply = function (effect) {
  78934. effect.setTexture("colorTable", _this._colorTableTexture);
  78935. };
  78936. return _this;
  78937. }
  78938. return ColorCorrectionPostProcess;
  78939. }(BABYLON.PostProcess));
  78940. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78941. })(BABYLON || (BABYLON = {}));
  78942. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78943. var BABYLON;
  78944. (function (BABYLON) {
  78945. /** Defines operator used for tonemapping */
  78946. var TonemappingOperator;
  78947. (function (TonemappingOperator) {
  78948. /** Hable */
  78949. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78950. /** Reinhard */
  78951. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78952. /** HejiDawson */
  78953. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78954. /** Photographic */
  78955. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78956. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78957. ;
  78958. /**
  78959. * Defines a post process to apply tone mapping
  78960. */
  78961. var TonemapPostProcess = /** @class */ (function (_super) {
  78962. __extends(TonemapPostProcess, _super);
  78963. /**
  78964. * Creates a new TonemapPostProcess
  78965. * @param name defines the name of the postprocess
  78966. * @param _operator defines the operator to use
  78967. * @param exposureAdjustment defines the required exposure adjustement
  78968. * @param camera defines the camera to use (can be null)
  78969. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78970. * @param engine defines the hosting engine (can be ignore if camera is set)
  78971. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78972. */
  78973. function TonemapPostProcess(name, _operator,
  78974. /** Defines the required exposure adjustement */
  78975. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78976. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78977. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78978. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78979. _this._operator = _operator;
  78980. _this.exposureAdjustment = exposureAdjustment;
  78981. var defines = "#define ";
  78982. if (_this._operator === TonemappingOperator.Hable)
  78983. defines += "HABLE_TONEMAPPING";
  78984. else if (_this._operator === TonemappingOperator.Reinhard)
  78985. defines += "REINHARD_TONEMAPPING";
  78986. else if (_this._operator === TonemappingOperator.HejiDawson)
  78987. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  78988. else if (_this._operator === TonemappingOperator.Photographic)
  78989. defines += "PHOTOGRAPHIC_TONEMAPPING";
  78990. //sadly a second call to create the effect.
  78991. _this.updateEffect(defines);
  78992. _this.onApply = function (effect) {
  78993. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  78994. };
  78995. return _this;
  78996. }
  78997. return TonemapPostProcess;
  78998. }(BABYLON.PostProcess));
  78999. BABYLON.TonemapPostProcess = TonemapPostProcess;
  79000. })(BABYLON || (BABYLON = {}));
  79001. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  79002. var BABYLON;
  79003. (function (BABYLON) {
  79004. var DisplayPassPostProcess = /** @class */ (function (_super) {
  79005. __extends(DisplayPassPostProcess, _super);
  79006. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  79007. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  79008. }
  79009. return DisplayPassPostProcess;
  79010. }(BABYLON.PostProcess));
  79011. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  79012. })(BABYLON || (BABYLON = {}));
  79013. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  79014. var BABYLON;
  79015. (function (BABYLON) {
  79016. var HighlightsPostProcess = /** @class */ (function (_super) {
  79017. __extends(HighlightsPostProcess, _super);
  79018. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79019. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79020. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79021. }
  79022. return HighlightsPostProcess;
  79023. }(BABYLON.PostProcess));
  79024. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  79025. })(BABYLON || (BABYLON = {}));
  79026. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  79027. var BABYLON;
  79028. (function (BABYLON) {
  79029. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  79030. __extends(ImageProcessingPostProcess, _super);
  79031. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  79032. if (camera === void 0) { camera = null; }
  79033. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79034. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  79035. _this._fromLinearSpace = true;
  79036. /**
  79037. * Defines cache preventing GC.
  79038. */
  79039. _this._defines = {
  79040. IMAGEPROCESSING: false,
  79041. VIGNETTE: false,
  79042. VIGNETTEBLENDMODEMULTIPLY: false,
  79043. VIGNETTEBLENDMODEOPAQUE: false,
  79044. TONEMAPPING: false,
  79045. CONTRAST: false,
  79046. COLORCURVES: false,
  79047. COLORGRADING: false,
  79048. COLORGRADING3D: false,
  79049. FROMLINEARSPACE: false,
  79050. SAMPLER3DGREENDEPTH: false,
  79051. SAMPLER3DBGRMAP: false,
  79052. IMAGEPROCESSINGPOSTPROCESS: false,
  79053. EXPOSURE: false,
  79054. };
  79055. // Setup the configuration as forced by the constructor. This would then not force the
  79056. // scene materials output in linear space and let untouched the default forward pass.
  79057. if (imageProcessingConfiguration) {
  79058. imageProcessingConfiguration.applyByPostProcess = true;
  79059. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  79060. // This will cause the shader to be compiled
  79061. _this.fromLinearSpace = false;
  79062. }
  79063. // Setup the default processing configuration to the scene.
  79064. else {
  79065. _this._attachImageProcessingConfiguration(null, true);
  79066. _this.imageProcessingConfiguration.applyByPostProcess = true;
  79067. }
  79068. _this.onApply = function (effect) {
  79069. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  79070. };
  79071. return _this;
  79072. }
  79073. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  79074. /**
  79075. * Gets the image processing configuration used either in this material.
  79076. */
  79077. get: function () {
  79078. return this._imageProcessingConfiguration;
  79079. },
  79080. /**
  79081. * Sets the Default image processing configuration used either in the this material.
  79082. *
  79083. * If sets to null, the scene one is in use.
  79084. */
  79085. set: function (value) {
  79086. this._attachImageProcessingConfiguration(value);
  79087. },
  79088. enumerable: true,
  79089. configurable: true
  79090. });
  79091. /**
  79092. * Attaches a new image processing configuration to the PBR Material.
  79093. * @param configuration
  79094. */
  79095. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  79096. var _this = this;
  79097. if (doNotBuild === void 0) { doNotBuild = false; }
  79098. if (configuration === this._imageProcessingConfiguration) {
  79099. return;
  79100. }
  79101. // Detaches observer.
  79102. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79103. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79104. }
  79105. // Pick the scene configuration if needed.
  79106. if (!configuration) {
  79107. var scene = null;
  79108. var engine = this.getEngine();
  79109. var camera = this.getCamera();
  79110. if (camera) {
  79111. scene = camera.getScene();
  79112. }
  79113. else if (engine && engine.scenes) {
  79114. var scenes = engine.scenes;
  79115. scene = scenes[scenes.length - 1];
  79116. }
  79117. else {
  79118. scene = BABYLON.Engine.LastCreatedScene;
  79119. }
  79120. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  79121. }
  79122. else {
  79123. this._imageProcessingConfiguration = configuration;
  79124. }
  79125. // Attaches observer.
  79126. if (this._imageProcessingConfiguration) {
  79127. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  79128. _this._updateParameters();
  79129. });
  79130. }
  79131. // Ensure the effect will be rebuilt.
  79132. if (!doNotBuild) {
  79133. this._updateParameters();
  79134. }
  79135. };
  79136. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  79137. /**
  79138. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79139. */
  79140. get: function () {
  79141. return this.imageProcessingConfiguration.colorCurves;
  79142. },
  79143. /**
  79144. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79145. */
  79146. set: function (value) {
  79147. this.imageProcessingConfiguration.colorCurves = value;
  79148. },
  79149. enumerable: true,
  79150. configurable: true
  79151. });
  79152. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  79153. /**
  79154. * Gets wether the color curves effect is enabled.
  79155. */
  79156. get: function () {
  79157. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79158. },
  79159. /**
  79160. * Sets wether the color curves effect is enabled.
  79161. */
  79162. set: function (value) {
  79163. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79164. },
  79165. enumerable: true,
  79166. configurable: true
  79167. });
  79168. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  79169. /**
  79170. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79171. */
  79172. get: function () {
  79173. return this.imageProcessingConfiguration.colorGradingTexture;
  79174. },
  79175. /**
  79176. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79177. */
  79178. set: function (value) {
  79179. this.imageProcessingConfiguration.colorGradingTexture = value;
  79180. },
  79181. enumerable: true,
  79182. configurable: true
  79183. });
  79184. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  79185. /**
  79186. * Gets wether the color grading effect is enabled.
  79187. */
  79188. get: function () {
  79189. return this.imageProcessingConfiguration.colorGradingEnabled;
  79190. },
  79191. /**
  79192. * Gets wether the color grading effect is enabled.
  79193. */
  79194. set: function (value) {
  79195. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79196. },
  79197. enumerable: true,
  79198. configurable: true
  79199. });
  79200. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  79201. /**
  79202. * Gets exposure used in the effect.
  79203. */
  79204. get: function () {
  79205. return this.imageProcessingConfiguration.exposure;
  79206. },
  79207. /**
  79208. * Sets exposure used in the effect.
  79209. */
  79210. set: function (value) {
  79211. this.imageProcessingConfiguration.exposure = value;
  79212. },
  79213. enumerable: true,
  79214. configurable: true
  79215. });
  79216. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79217. /**
  79218. * Gets wether tonemapping is enabled or not.
  79219. */
  79220. get: function () {
  79221. return this._imageProcessingConfiguration.toneMappingEnabled;
  79222. },
  79223. /**
  79224. * Sets wether tonemapping is enabled or not
  79225. */
  79226. set: function (value) {
  79227. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79228. },
  79229. enumerable: true,
  79230. configurable: true
  79231. });
  79232. ;
  79233. ;
  79234. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79235. /**
  79236. * Gets contrast used in the effect.
  79237. */
  79238. get: function () {
  79239. return this.imageProcessingConfiguration.contrast;
  79240. },
  79241. /**
  79242. * Sets contrast used in the effect.
  79243. */
  79244. set: function (value) {
  79245. this.imageProcessingConfiguration.contrast = value;
  79246. },
  79247. enumerable: true,
  79248. configurable: true
  79249. });
  79250. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79251. /**
  79252. * Gets Vignette stretch size.
  79253. */
  79254. get: function () {
  79255. return this.imageProcessingConfiguration.vignetteStretch;
  79256. },
  79257. /**
  79258. * Sets Vignette stretch size.
  79259. */
  79260. set: function (value) {
  79261. this.imageProcessingConfiguration.vignetteStretch = value;
  79262. },
  79263. enumerable: true,
  79264. configurable: true
  79265. });
  79266. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79267. /**
  79268. * Gets Vignette centre X Offset.
  79269. */
  79270. get: function () {
  79271. return this.imageProcessingConfiguration.vignetteCentreX;
  79272. },
  79273. /**
  79274. * Sets Vignette centre X Offset.
  79275. */
  79276. set: function (value) {
  79277. this.imageProcessingConfiguration.vignetteCentreX = value;
  79278. },
  79279. enumerable: true,
  79280. configurable: true
  79281. });
  79282. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79283. /**
  79284. * Gets Vignette centre Y Offset.
  79285. */
  79286. get: function () {
  79287. return this.imageProcessingConfiguration.vignetteCentreY;
  79288. },
  79289. /**
  79290. * Sets Vignette centre Y Offset.
  79291. */
  79292. set: function (value) {
  79293. this.imageProcessingConfiguration.vignetteCentreY = value;
  79294. },
  79295. enumerable: true,
  79296. configurable: true
  79297. });
  79298. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79299. /**
  79300. * Gets Vignette weight or intensity of the vignette effect.
  79301. */
  79302. get: function () {
  79303. return this.imageProcessingConfiguration.vignetteWeight;
  79304. },
  79305. /**
  79306. * Sets Vignette weight or intensity of the vignette effect.
  79307. */
  79308. set: function (value) {
  79309. this.imageProcessingConfiguration.vignetteWeight = value;
  79310. },
  79311. enumerable: true,
  79312. configurable: true
  79313. });
  79314. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79315. /**
  79316. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79317. * if vignetteEnabled is set to true.
  79318. */
  79319. get: function () {
  79320. return this.imageProcessingConfiguration.vignetteColor;
  79321. },
  79322. /**
  79323. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79324. * if vignetteEnabled is set to true.
  79325. */
  79326. set: function (value) {
  79327. this.imageProcessingConfiguration.vignetteColor = value;
  79328. },
  79329. enumerable: true,
  79330. configurable: true
  79331. });
  79332. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79333. /**
  79334. * Gets Camera field of view used by the Vignette effect.
  79335. */
  79336. get: function () {
  79337. return this.imageProcessingConfiguration.vignetteCameraFov;
  79338. },
  79339. /**
  79340. * Sets Camera field of view used by the Vignette effect.
  79341. */
  79342. set: function (value) {
  79343. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79344. },
  79345. enumerable: true,
  79346. configurable: true
  79347. });
  79348. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79349. /**
  79350. * Gets the vignette blend mode allowing different kind of effect.
  79351. */
  79352. get: function () {
  79353. return this.imageProcessingConfiguration.vignetteBlendMode;
  79354. },
  79355. /**
  79356. * Sets the vignette blend mode allowing different kind of effect.
  79357. */
  79358. set: function (value) {
  79359. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79360. },
  79361. enumerable: true,
  79362. configurable: true
  79363. });
  79364. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79365. /**
  79366. * Gets wether the vignette effect is enabled.
  79367. */
  79368. get: function () {
  79369. return this.imageProcessingConfiguration.vignetteEnabled;
  79370. },
  79371. /**
  79372. * Sets wether the vignette effect is enabled.
  79373. */
  79374. set: function (value) {
  79375. this.imageProcessingConfiguration.vignetteEnabled = value;
  79376. },
  79377. enumerable: true,
  79378. configurable: true
  79379. });
  79380. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79381. /**
  79382. * Gets wether the input of the processing is in Gamma or Linear Space.
  79383. */
  79384. get: function () {
  79385. return this._fromLinearSpace;
  79386. },
  79387. /**
  79388. * Sets wether the input of the processing is in Gamma or Linear Space.
  79389. */
  79390. set: function (value) {
  79391. if (this._fromLinearSpace === value) {
  79392. return;
  79393. }
  79394. this._fromLinearSpace = value;
  79395. this._updateParameters();
  79396. },
  79397. enumerable: true,
  79398. configurable: true
  79399. });
  79400. ImageProcessingPostProcess.prototype.getClassName = function () {
  79401. return "ImageProcessingPostProcess";
  79402. };
  79403. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79404. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79405. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79406. var defines = "";
  79407. for (var define in this._defines) {
  79408. if (this._defines[define]) {
  79409. defines += "#define " + define + ";\r\n";
  79410. }
  79411. }
  79412. var samplers = ["textureSampler"];
  79413. var uniforms = ["scale"];
  79414. if (BABYLON.ImageProcessingConfiguration) {
  79415. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79416. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79417. }
  79418. this.updateEffect(defines, uniforms, samplers);
  79419. };
  79420. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79421. _super.prototype.dispose.call(this, camera);
  79422. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79423. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79424. }
  79425. if (this._imageProcessingConfiguration) {
  79426. this.imageProcessingConfiguration.applyByPostProcess = false;
  79427. }
  79428. };
  79429. __decorate([
  79430. BABYLON.serialize()
  79431. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79432. return ImageProcessingPostProcess;
  79433. }(BABYLON.PostProcess));
  79434. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79435. })(BABYLON || (BABYLON = {}));
  79436. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79437. var BABYLON;
  79438. (function (BABYLON) {
  79439. /**
  79440. * Class used to store bone information
  79441. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79442. */
  79443. var Bone = /** @class */ (function (_super) {
  79444. __extends(Bone, _super);
  79445. /**
  79446. * Create a new bone
  79447. * @param name defines the bone name
  79448. * @param skeleton defines the parent skeleton
  79449. * @param parentBone defines the parent (can be null if the bone is the root)
  79450. * @param localMatrix defines the local matrix
  79451. * @param restPose defines the rest pose matrix
  79452. * @param baseMatrix defines the base matrix
  79453. * @param index defines index of the bone in the hiearchy
  79454. */
  79455. function Bone(
  79456. /**
  79457. * defines the bone name
  79458. */
  79459. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79460. if (parentBone === void 0) { parentBone = null; }
  79461. if (localMatrix === void 0) { localMatrix = null; }
  79462. if (restPose === void 0) { restPose = null; }
  79463. if (baseMatrix === void 0) { baseMatrix = null; }
  79464. if (index === void 0) { index = null; }
  79465. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79466. _this.name = name;
  79467. /**
  79468. * Gets the list of child bones
  79469. */
  79470. _this.children = new Array();
  79471. /** Gets the animations associated with this bone */
  79472. _this.animations = new Array();
  79473. /**
  79474. * @hidden Internal only
  79475. * Set this value to map this bone to a different index in the transform matrices
  79476. * Set this value to -1 to exclude the bone from the transform matrices
  79477. */
  79478. _this._index = null;
  79479. _this._absoluteTransform = new BABYLON.Matrix();
  79480. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79481. _this._scalingDeterminant = 1;
  79482. _this._worldTransform = new BABYLON.Matrix();
  79483. _this._needToDecompose = true;
  79484. _this._needToCompose = false;
  79485. _this._skeleton = skeleton;
  79486. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79487. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79488. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79489. _this._index = index;
  79490. skeleton.bones.push(_this);
  79491. _this.setParent(parentBone, false);
  79492. if (baseMatrix || localMatrix) {
  79493. _this._updateDifferenceMatrix();
  79494. }
  79495. return _this;
  79496. }
  79497. Object.defineProperty(Bone.prototype, "_matrix", {
  79498. /** @hidden */
  79499. get: function () {
  79500. this._compose();
  79501. return this._localMatrix;
  79502. },
  79503. /** @hidden */
  79504. set: function (value) {
  79505. this._localMatrix.copyFrom(value);
  79506. this._needToDecompose = true;
  79507. },
  79508. enumerable: true,
  79509. configurable: true
  79510. });
  79511. // Members
  79512. /**
  79513. * Gets the parent skeleton
  79514. * @returns a skeleton
  79515. */
  79516. Bone.prototype.getSkeleton = function () {
  79517. return this._skeleton;
  79518. };
  79519. /**
  79520. * Gets parent bone
  79521. * @returns a bone or null if the bone is the root of the bone hierarchy
  79522. */
  79523. Bone.prototype.getParent = function () {
  79524. return this._parent;
  79525. };
  79526. /**
  79527. * Sets the parent bone
  79528. * @param parent defines the parent (can be null if the bone is the root)
  79529. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79530. */
  79531. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79532. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79533. if (this._parent === parent) {
  79534. return;
  79535. }
  79536. if (this._parent) {
  79537. var index = this._parent.children.indexOf(this);
  79538. if (index !== -1) {
  79539. this._parent.children.splice(index, 1);
  79540. }
  79541. }
  79542. this._parent = parent;
  79543. if (this._parent) {
  79544. this._parent.children.push(this);
  79545. }
  79546. if (updateDifferenceMatrix) {
  79547. this._updateDifferenceMatrix();
  79548. }
  79549. this.markAsDirty();
  79550. };
  79551. /**
  79552. * Gets the local matrix
  79553. * @returns a matrix
  79554. */
  79555. Bone.prototype.getLocalMatrix = function () {
  79556. this._compose();
  79557. return this._localMatrix;
  79558. };
  79559. /**
  79560. * Gets the base matrix (initial matrix which remains unchanged)
  79561. * @returns a matrix
  79562. */
  79563. Bone.prototype.getBaseMatrix = function () {
  79564. return this._baseMatrix;
  79565. };
  79566. /**
  79567. * Gets the rest pose matrix
  79568. * @returns a matrix
  79569. */
  79570. Bone.prototype.getRestPose = function () {
  79571. return this._restPose;
  79572. };
  79573. /**
  79574. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79575. */
  79576. Bone.prototype.getWorldMatrix = function () {
  79577. return this._worldTransform;
  79578. };
  79579. /**
  79580. * Sets the local matrix to rest pose matrix
  79581. */
  79582. Bone.prototype.returnToRest = function () {
  79583. this.updateMatrix(this._restPose.clone());
  79584. };
  79585. /**
  79586. * Gets the inverse of the absolute transform matrix.
  79587. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79588. * @returns a matrix
  79589. */
  79590. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79591. return this._invertedAbsoluteTransform;
  79592. };
  79593. /**
  79594. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79595. * @returns a matrix
  79596. */
  79597. Bone.prototype.getAbsoluteTransform = function () {
  79598. return this._absoluteTransform;
  79599. };
  79600. Object.defineProperty(Bone.prototype, "position", {
  79601. // Properties (matches AbstractMesh properties)
  79602. /** Gets or sets current position (in local space) */
  79603. get: function () {
  79604. this._decompose();
  79605. return this._localPosition;
  79606. },
  79607. set: function (newPosition) {
  79608. this._decompose();
  79609. this._localPosition.copyFrom(newPosition);
  79610. this._markAsDirtyAndCompose();
  79611. },
  79612. enumerable: true,
  79613. configurable: true
  79614. });
  79615. Object.defineProperty(Bone.prototype, "rotation", {
  79616. /** Gets or sets current rotation (in local space) */
  79617. get: function () {
  79618. return this.getRotation();
  79619. },
  79620. set: function (newRotation) {
  79621. this.setRotation(newRotation);
  79622. },
  79623. enumerable: true,
  79624. configurable: true
  79625. });
  79626. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79627. /** Gets or sets current rotation quaternion (in local space) */
  79628. get: function () {
  79629. this._decompose();
  79630. return this._localRotation;
  79631. },
  79632. set: function (newRotation) {
  79633. this.setRotationQuaternion(newRotation);
  79634. },
  79635. enumerable: true,
  79636. configurable: true
  79637. });
  79638. Object.defineProperty(Bone.prototype, "scaling", {
  79639. /** Gets or sets current scaling (in local space) */
  79640. get: function () {
  79641. return this.getScale();
  79642. },
  79643. set: function (newScaling) {
  79644. this.setScale(newScaling);
  79645. },
  79646. enumerable: true,
  79647. configurable: true
  79648. });
  79649. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79650. /**
  79651. * Gets the animation properties override
  79652. */
  79653. get: function () {
  79654. return this._skeleton.animationPropertiesOverride;
  79655. },
  79656. enumerable: true,
  79657. configurable: true
  79658. });
  79659. // Methods
  79660. Bone.prototype._decompose = function () {
  79661. if (!this._needToDecompose) {
  79662. return;
  79663. }
  79664. this._needToDecompose = false;
  79665. if (!this._localScaling) {
  79666. this._localScaling = BABYLON.Vector3.Zero();
  79667. this._localRotation = BABYLON.Quaternion.Zero();
  79668. this._localPosition = BABYLON.Vector3.Zero();
  79669. }
  79670. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79671. };
  79672. Bone.prototype._compose = function () {
  79673. if (!this._needToCompose) {
  79674. return;
  79675. }
  79676. this._needToCompose = false;
  79677. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79678. };
  79679. /**
  79680. * Update the base and local matrices
  79681. * @param matrix defines the new base or local matrix
  79682. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79683. * @param updateLocalMatrix defines if the local matrix should be updated
  79684. */
  79685. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79686. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79687. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79688. this._baseMatrix.copyFrom(matrix);
  79689. if (updateDifferenceMatrix) {
  79690. this._updateDifferenceMatrix();
  79691. }
  79692. if (updateLocalMatrix) {
  79693. this._localMatrix.copyFrom(matrix);
  79694. this._markAsDirtyAndDecompose();
  79695. }
  79696. else {
  79697. this.markAsDirty();
  79698. }
  79699. };
  79700. /** @hidden */
  79701. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79702. if (updateChildren === void 0) { updateChildren = true; }
  79703. if (!rootMatrix) {
  79704. rootMatrix = this._baseMatrix;
  79705. }
  79706. if (this._parent) {
  79707. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79708. }
  79709. else {
  79710. this._absoluteTransform.copyFrom(rootMatrix);
  79711. }
  79712. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79713. if (updateChildren) {
  79714. for (var index = 0; index < this.children.length; index++) {
  79715. this.children[index]._updateDifferenceMatrix();
  79716. }
  79717. }
  79718. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79719. };
  79720. /**
  79721. * Flag the bone as dirty (Forcing it to update everything)
  79722. */
  79723. Bone.prototype.markAsDirty = function () {
  79724. this._currentRenderId++;
  79725. this._childRenderId++;
  79726. this._skeleton._markAsDirty();
  79727. };
  79728. Bone.prototype._markAsDirtyAndCompose = function () {
  79729. this.markAsDirty();
  79730. this._needToCompose = true;
  79731. };
  79732. Bone.prototype._markAsDirtyAndDecompose = function () {
  79733. this.markAsDirty();
  79734. this._needToDecompose = true;
  79735. };
  79736. /**
  79737. * Copy an animation range from another bone
  79738. * @param source defines the source bone
  79739. * @param rangeName defines the range name to copy
  79740. * @param frameOffset defines the frame offset
  79741. * @param rescaleAsRequired defines if rescaling must be applied if required
  79742. * @param skelDimensionsRatio defines the scaling ratio
  79743. * @returns true if operation was successful
  79744. */
  79745. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79746. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79747. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79748. // all animation may be coming from a library skeleton, so may need to create animation
  79749. if (this.animations.length === 0) {
  79750. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79751. this.animations[0].setKeys([]);
  79752. }
  79753. // get animation info / verify there is such a range from the source bone
  79754. var sourceRange = source.animations[0].getRange(rangeName);
  79755. if (!sourceRange) {
  79756. return false;
  79757. }
  79758. var from = sourceRange.from;
  79759. var to = sourceRange.to;
  79760. var sourceKeys = source.animations[0].getKeys();
  79761. // rescaling prep
  79762. var sourceBoneLength = source.length;
  79763. var sourceParent = source.getParent();
  79764. var parent = this.getParent();
  79765. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79766. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79767. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79768. var destKeys = this.animations[0].getKeys();
  79769. // loop vars declaration
  79770. var orig;
  79771. var origTranslation;
  79772. var mat;
  79773. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79774. orig = sourceKeys[key];
  79775. if (orig.frame >= from && orig.frame <= to) {
  79776. if (rescaleAsRequired) {
  79777. mat = orig.value.clone();
  79778. // scale based on parent ratio, when bone has parent
  79779. if (parentScalingReqd) {
  79780. origTranslation = mat.getTranslation();
  79781. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79782. // scale based on skeleton dimension ratio when root bone, and value is passed
  79783. }
  79784. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79785. origTranslation = mat.getTranslation();
  79786. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79787. // use original when root bone, and no data for skelDimensionsRatio
  79788. }
  79789. else {
  79790. mat = orig.value;
  79791. }
  79792. }
  79793. else {
  79794. mat = orig.value;
  79795. }
  79796. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79797. }
  79798. }
  79799. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79800. return true;
  79801. };
  79802. /**
  79803. * Translate the bone in local or world space
  79804. * @param vec The amount to translate the bone
  79805. * @param space The space that the translation is in
  79806. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79807. */
  79808. Bone.prototype.translate = function (vec, space, mesh) {
  79809. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79810. var lm = this.getLocalMatrix();
  79811. if (space == BABYLON.Space.LOCAL) {
  79812. lm.m[12] += vec.x;
  79813. lm.m[13] += vec.y;
  79814. lm.m[14] += vec.z;
  79815. }
  79816. else {
  79817. var wm = null;
  79818. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79819. if (mesh) {
  79820. wm = mesh.getWorldMatrix();
  79821. }
  79822. this._skeleton.computeAbsoluteTransforms();
  79823. var tmat = Bone._tmpMats[0];
  79824. var tvec = Bone._tmpVecs[0];
  79825. if (this._parent) {
  79826. if (mesh && wm) {
  79827. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79828. tmat.multiplyToRef(wm, tmat);
  79829. }
  79830. else {
  79831. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79832. }
  79833. }
  79834. tmat.m[12] = 0;
  79835. tmat.m[13] = 0;
  79836. tmat.m[14] = 0;
  79837. tmat.invert();
  79838. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79839. lm.m[12] += tvec.x;
  79840. lm.m[13] += tvec.y;
  79841. lm.m[14] += tvec.z;
  79842. }
  79843. this._markAsDirtyAndDecompose();
  79844. };
  79845. /**
  79846. * Set the postion of the bone in local or world space
  79847. * @param position The position to set the bone
  79848. * @param space The space that the position is in
  79849. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79850. */
  79851. Bone.prototype.setPosition = function (position, space, mesh) {
  79852. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79853. var lm = this.getLocalMatrix();
  79854. if (space == BABYLON.Space.LOCAL) {
  79855. lm.m[12] = position.x;
  79856. lm.m[13] = position.y;
  79857. lm.m[14] = position.z;
  79858. }
  79859. else {
  79860. var wm = null;
  79861. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79862. if (mesh) {
  79863. wm = mesh.getWorldMatrix();
  79864. }
  79865. this._skeleton.computeAbsoluteTransforms();
  79866. var tmat = Bone._tmpMats[0];
  79867. var vec = Bone._tmpVecs[0];
  79868. if (this._parent) {
  79869. if (mesh && wm) {
  79870. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79871. tmat.multiplyToRef(wm, tmat);
  79872. }
  79873. else {
  79874. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79875. }
  79876. }
  79877. tmat.invert();
  79878. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79879. lm.m[12] = vec.x;
  79880. lm.m[13] = vec.y;
  79881. lm.m[14] = vec.z;
  79882. }
  79883. this._markAsDirtyAndDecompose();
  79884. };
  79885. /**
  79886. * Set the absolute position of the bone (world space)
  79887. * @param position The position to set the bone
  79888. * @param mesh The mesh that this bone is attached to
  79889. */
  79890. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79891. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79892. };
  79893. /**
  79894. * Scale the bone on the x, y and z axes (in local space)
  79895. * @param x The amount to scale the bone on the x axis
  79896. * @param y The amount to scale the bone on the y axis
  79897. * @param z The amount to scale the bone on the z axis
  79898. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79899. */
  79900. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79901. if (scaleChildren === void 0) { scaleChildren = false; }
  79902. var locMat = this.getLocalMatrix();
  79903. // Apply new scaling on top of current local matrix
  79904. var scaleMat = Bone._tmpMats[0];
  79905. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79906. scaleMat.multiplyToRef(locMat, locMat);
  79907. // Invert scaling matrix and apply the inverse to all children
  79908. scaleMat.invert();
  79909. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79910. var child = _a[_i];
  79911. var cm = child.getLocalMatrix();
  79912. cm.multiplyToRef(scaleMat, cm);
  79913. cm.m[12] *= x;
  79914. cm.m[13] *= y;
  79915. cm.m[14] *= z;
  79916. child._markAsDirtyAndDecompose();
  79917. }
  79918. this._markAsDirtyAndDecompose();
  79919. if (scaleChildren) {
  79920. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79921. var child = _c[_b];
  79922. child.scale(x, y, z, scaleChildren);
  79923. }
  79924. }
  79925. };
  79926. /**
  79927. * Set the bone scaling in local space
  79928. * @param scale defines the scaling vector
  79929. */
  79930. Bone.prototype.setScale = function (scale) {
  79931. this._decompose();
  79932. this._localScaling.copyFrom(scale);
  79933. this._markAsDirtyAndCompose();
  79934. };
  79935. /**
  79936. * Gets the current scaling in local space
  79937. * @returns the current scaling vector
  79938. */
  79939. Bone.prototype.getScale = function () {
  79940. this._decompose();
  79941. return this._localScaling;
  79942. };
  79943. /**
  79944. * Gets the current scaling in local space and stores it in a target vector
  79945. * @param result defines the target vector
  79946. */
  79947. Bone.prototype.getScaleToRef = function (result) {
  79948. this._decompose();
  79949. result.copyFrom(this._localScaling);
  79950. };
  79951. /**
  79952. * Set the yaw, pitch, and roll of the bone in local or world space
  79953. * @param yaw The rotation of the bone on the y axis
  79954. * @param pitch The rotation of the bone on the x axis
  79955. * @param roll The rotation of the bone on the z axis
  79956. * @param space The space that the axes of rotation are in
  79957. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79958. */
  79959. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79960. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79961. if (space === BABYLON.Space.LOCAL) {
  79962. var quat = Bone._tmpQuat;
  79963. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79964. this.setRotationQuaternion(quat, space, mesh);
  79965. return;
  79966. }
  79967. var rotMatInv = Bone._tmpMats[0];
  79968. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79969. return;
  79970. }
  79971. var rotMat = Bone._tmpMats[1];
  79972. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79973. rotMatInv.multiplyToRef(rotMat, rotMat);
  79974. this._rotateWithMatrix(rotMat, space, mesh);
  79975. };
  79976. /**
  79977. * Add a rotation to the bone on an axis in local or world space
  79978. * @param axis The axis to rotate the bone on
  79979. * @param amount The amount to rotate the bone
  79980. * @param space The space that the axis is in
  79981. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79982. */
  79983. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  79984. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79985. var rmat = Bone._tmpMats[0];
  79986. rmat.m[12] = 0;
  79987. rmat.m[13] = 0;
  79988. rmat.m[14] = 0;
  79989. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  79990. this._rotateWithMatrix(rmat, space, mesh);
  79991. };
  79992. /**
  79993. * Set the rotation of the bone to a particular axis angle in local or world space
  79994. * @param axis The axis to rotate the bone on
  79995. * @param angle The angle that the bone should be rotated to
  79996. * @param space The space that the axis is in
  79997. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79998. */
  79999. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  80000. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80001. if (space === BABYLON.Space.LOCAL) {
  80002. var quat = Bone._tmpQuat;
  80003. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  80004. this.setRotationQuaternion(quat, space, mesh);
  80005. return;
  80006. }
  80007. var rotMatInv = Bone._tmpMats[0];
  80008. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80009. return;
  80010. }
  80011. var rotMat = Bone._tmpMats[1];
  80012. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  80013. rotMatInv.multiplyToRef(rotMat, rotMat);
  80014. this._rotateWithMatrix(rotMat, space, mesh);
  80015. };
  80016. /**
  80017. * Set the euler rotation of the bone in local of world space
  80018. * @param rotation The euler rotation that the bone should be set to
  80019. * @param space The space that the rotation is in
  80020. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80021. */
  80022. Bone.prototype.setRotation = function (rotation, space, mesh) {
  80023. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80024. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  80025. };
  80026. /**
  80027. * Set the quaternion rotation of the bone in local of world space
  80028. * @param quat The quaternion rotation that the bone should be set to
  80029. * @param space The space that the rotation is in
  80030. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80031. */
  80032. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  80033. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80034. if (space === BABYLON.Space.LOCAL) {
  80035. this._decompose();
  80036. this._localRotation.copyFrom(quat);
  80037. this._markAsDirtyAndCompose();
  80038. return;
  80039. }
  80040. var rotMatInv = Bone._tmpMats[0];
  80041. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80042. return;
  80043. }
  80044. var rotMat = Bone._tmpMats[1];
  80045. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  80046. rotMatInv.multiplyToRef(rotMat, rotMat);
  80047. this._rotateWithMatrix(rotMat, space, mesh);
  80048. };
  80049. /**
  80050. * Set the rotation matrix of the bone in local of world space
  80051. * @param rotMat The rotation matrix that the bone should be set to
  80052. * @param space The space that the rotation is in
  80053. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80054. */
  80055. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  80056. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80057. if (space === BABYLON.Space.LOCAL) {
  80058. var quat = Bone._tmpQuat;
  80059. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  80060. this.setRotationQuaternion(quat, space, mesh);
  80061. return;
  80062. }
  80063. var rotMatInv = Bone._tmpMats[0];
  80064. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80065. return;
  80066. }
  80067. var rotMat2 = Bone._tmpMats[1];
  80068. rotMat2.copyFrom(rotMat);
  80069. rotMatInv.multiplyToRef(rotMat, rotMat2);
  80070. this._rotateWithMatrix(rotMat2, space, mesh);
  80071. };
  80072. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  80073. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80074. var lmat = this.getLocalMatrix();
  80075. var lx = lmat.m[12];
  80076. var ly = lmat.m[13];
  80077. var lz = lmat.m[14];
  80078. var parent = this.getParent();
  80079. var parentScale = Bone._tmpMats[3];
  80080. var parentScaleInv = Bone._tmpMats[4];
  80081. if (parent && space == BABYLON.Space.WORLD) {
  80082. if (mesh) {
  80083. parentScale.copyFrom(mesh.getWorldMatrix());
  80084. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  80085. }
  80086. else {
  80087. parentScale.copyFrom(parent.getAbsoluteTransform());
  80088. }
  80089. parentScaleInv.copyFrom(parentScale);
  80090. parentScaleInv.invert();
  80091. lmat.multiplyToRef(parentScale, lmat);
  80092. lmat.multiplyToRef(rmat, lmat);
  80093. lmat.multiplyToRef(parentScaleInv, lmat);
  80094. }
  80095. else {
  80096. if (space == BABYLON.Space.WORLD && mesh) {
  80097. parentScale.copyFrom(mesh.getWorldMatrix());
  80098. parentScaleInv.copyFrom(parentScale);
  80099. parentScaleInv.invert();
  80100. lmat.multiplyToRef(parentScale, lmat);
  80101. lmat.multiplyToRef(rmat, lmat);
  80102. lmat.multiplyToRef(parentScaleInv, lmat);
  80103. }
  80104. else {
  80105. lmat.multiplyToRef(rmat, lmat);
  80106. }
  80107. }
  80108. lmat.m[12] = lx;
  80109. lmat.m[13] = ly;
  80110. lmat.m[14] = lz;
  80111. this.computeAbsoluteTransforms();
  80112. this._markAsDirtyAndDecompose();
  80113. };
  80114. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  80115. var scaleMatrix = Bone._tmpMats[2];
  80116. rotMatInv.copyFrom(this.getAbsoluteTransform());
  80117. if (mesh) {
  80118. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  80119. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  80120. }
  80121. rotMatInv.invert();
  80122. if (isNaN(rotMatInv.m[0])) {
  80123. // Matrix failed to invert.
  80124. // This can happen if scale is zero for example.
  80125. return false;
  80126. }
  80127. scaleMatrix.m[0] *= this._scalingDeterminant;
  80128. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  80129. return true;
  80130. };
  80131. /**
  80132. * Get the position of the bone in local or world space
  80133. * @param space The space that the returned position is in
  80134. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80135. * @returns The position of the bone
  80136. */
  80137. Bone.prototype.getPosition = function (space, mesh) {
  80138. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80139. if (mesh === void 0) { mesh = null; }
  80140. var pos = BABYLON.Vector3.Zero();
  80141. this.getPositionToRef(space, mesh, pos);
  80142. return pos;
  80143. };
  80144. /**
  80145. * Copy the position of the bone to a vector3 in local or world space
  80146. * @param space The space that the returned position is in
  80147. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80148. * @param result The vector3 to copy the position to
  80149. */
  80150. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  80151. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80152. if (space == BABYLON.Space.LOCAL) {
  80153. var lm = this.getLocalMatrix();
  80154. result.x = lm.m[12];
  80155. result.y = lm.m[13];
  80156. result.z = lm.m[14];
  80157. }
  80158. else {
  80159. var wm = null;
  80160. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80161. if (mesh) {
  80162. wm = mesh.getWorldMatrix();
  80163. }
  80164. this._skeleton.computeAbsoluteTransforms();
  80165. var tmat = Bone._tmpMats[0];
  80166. if (mesh && wm) {
  80167. tmat.copyFrom(this.getAbsoluteTransform());
  80168. tmat.multiplyToRef(wm, tmat);
  80169. }
  80170. else {
  80171. tmat = this.getAbsoluteTransform();
  80172. }
  80173. result.x = tmat.m[12];
  80174. result.y = tmat.m[13];
  80175. result.z = tmat.m[14];
  80176. }
  80177. };
  80178. /**
  80179. * Get the absolute position of the bone (world space)
  80180. * @param mesh The mesh that this bone is attached to
  80181. * @returns The absolute position of the bone
  80182. */
  80183. Bone.prototype.getAbsolutePosition = function (mesh) {
  80184. if (mesh === void 0) { mesh = null; }
  80185. var pos = BABYLON.Vector3.Zero();
  80186. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  80187. return pos;
  80188. };
  80189. /**
  80190. * Copy the absolute position of the bone (world space) to the result param
  80191. * @param mesh The mesh that this bone is attached to
  80192. * @param result The vector3 to copy the absolute position to
  80193. */
  80194. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  80195. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  80196. };
  80197. /**
  80198. * Compute the absolute transforms of this bone and its children
  80199. */
  80200. Bone.prototype.computeAbsoluteTransforms = function () {
  80201. this._compose();
  80202. if (this._parent) {
  80203. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80204. }
  80205. else {
  80206. this._absoluteTransform.copyFrom(this._localMatrix);
  80207. var poseMatrix = this._skeleton.getPoseMatrix();
  80208. if (poseMatrix) {
  80209. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80210. }
  80211. }
  80212. var children = this.children;
  80213. var len = children.length;
  80214. for (var i = 0; i < len; i++) {
  80215. children[i].computeAbsoluteTransforms();
  80216. }
  80217. };
  80218. /**
  80219. * Get the world direction from an axis that is in the local space of the bone
  80220. * @param localAxis The local direction that is used to compute the world direction
  80221. * @param mesh The mesh that this bone is attached to
  80222. * @returns The world direction
  80223. */
  80224. Bone.prototype.getDirection = function (localAxis, mesh) {
  80225. if (mesh === void 0) { mesh = null; }
  80226. var result = BABYLON.Vector3.Zero();
  80227. this.getDirectionToRef(localAxis, mesh, result);
  80228. return result;
  80229. };
  80230. /**
  80231. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80232. * @param localAxis The local direction that is used to compute the world direction
  80233. * @param mesh The mesh that this bone is attached to
  80234. * @param result The vector3 that the world direction will be copied to
  80235. */
  80236. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80237. if (mesh === void 0) { mesh = null; }
  80238. var wm = null;
  80239. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80240. if (mesh) {
  80241. wm = mesh.getWorldMatrix();
  80242. }
  80243. this._skeleton.computeAbsoluteTransforms();
  80244. var mat = Bone._tmpMats[0];
  80245. mat.copyFrom(this.getAbsoluteTransform());
  80246. if (mesh && wm) {
  80247. mat.multiplyToRef(wm, mat);
  80248. }
  80249. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80250. result.normalize();
  80251. };
  80252. /**
  80253. * Get the euler rotation of the bone in local or world space
  80254. * @param space The space that the rotation should be in
  80255. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80256. * @returns The euler rotation
  80257. */
  80258. Bone.prototype.getRotation = function (space, mesh) {
  80259. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80260. if (mesh === void 0) { mesh = null; }
  80261. var result = BABYLON.Vector3.Zero();
  80262. this.getRotationToRef(space, mesh, result);
  80263. return result;
  80264. };
  80265. /**
  80266. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80267. * @param space The space that the rotation should be in
  80268. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80269. * @param result The vector3 that the rotation should be copied to
  80270. */
  80271. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80272. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80273. if (mesh === void 0) { mesh = null; }
  80274. var quat = Bone._tmpQuat;
  80275. this.getRotationQuaternionToRef(space, mesh, quat);
  80276. quat.toEulerAnglesToRef(result);
  80277. };
  80278. /**
  80279. * Get the quaternion rotation of the bone in either local or world space
  80280. * @param space The space that the rotation should be in
  80281. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80282. * @returns The quaternion rotation
  80283. */
  80284. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80285. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80286. if (mesh === void 0) { mesh = null; }
  80287. var result = BABYLON.Quaternion.Identity();
  80288. this.getRotationQuaternionToRef(space, mesh, result);
  80289. return result;
  80290. };
  80291. /**
  80292. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80293. * @param space The space that the rotation should be in
  80294. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80295. * @param result The quaternion that the rotation should be copied to
  80296. */
  80297. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80298. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80299. if (mesh === void 0) { mesh = null; }
  80300. if (space == BABYLON.Space.LOCAL) {
  80301. this._decompose();
  80302. result.copyFrom(this._localRotation);
  80303. }
  80304. else {
  80305. var mat = Bone._tmpMats[0];
  80306. var amat = this.getAbsoluteTransform();
  80307. if (mesh) {
  80308. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80309. }
  80310. else {
  80311. mat.copyFrom(amat);
  80312. }
  80313. mat.m[0] *= this._scalingDeterminant;
  80314. mat.m[1] *= this._scalingDeterminant;
  80315. mat.m[2] *= this._scalingDeterminant;
  80316. mat.decompose(undefined, result, undefined);
  80317. }
  80318. };
  80319. /**
  80320. * Get the rotation matrix of the bone in local or world space
  80321. * @param space The space that the rotation should be in
  80322. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80323. * @returns The rotation matrix
  80324. */
  80325. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80326. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80327. var result = BABYLON.Matrix.Identity();
  80328. this.getRotationMatrixToRef(space, mesh, result);
  80329. return result;
  80330. };
  80331. /**
  80332. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80333. * @param space The space that the rotation should be in
  80334. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80335. * @param result The quaternion that the rotation should be copied to
  80336. */
  80337. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80338. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80339. if (space == BABYLON.Space.LOCAL) {
  80340. this.getLocalMatrix().getRotationMatrixToRef(result);
  80341. }
  80342. else {
  80343. var mat = Bone._tmpMats[0];
  80344. var amat = this.getAbsoluteTransform();
  80345. if (mesh) {
  80346. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80347. }
  80348. else {
  80349. mat.copyFrom(amat);
  80350. }
  80351. mat.m[0] *= this._scalingDeterminant;
  80352. mat.m[1] *= this._scalingDeterminant;
  80353. mat.m[2] *= this._scalingDeterminant;
  80354. mat.getRotationMatrixToRef(result);
  80355. }
  80356. };
  80357. /**
  80358. * Get the world position of a point that is in the local space of the bone
  80359. * @param position The local position
  80360. * @param mesh The mesh that this bone is attached to
  80361. * @returns The world position
  80362. */
  80363. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80364. if (mesh === void 0) { mesh = null; }
  80365. var result = BABYLON.Vector3.Zero();
  80366. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80367. return result;
  80368. };
  80369. /**
  80370. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80371. * @param position The local position
  80372. * @param mesh The mesh that this bone is attached to
  80373. * @param result The vector3 that the world position should be copied to
  80374. */
  80375. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80376. if (mesh === void 0) { mesh = null; }
  80377. var wm = null;
  80378. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80379. if (mesh) {
  80380. wm = mesh.getWorldMatrix();
  80381. }
  80382. this._skeleton.computeAbsoluteTransforms();
  80383. var tmat = Bone._tmpMats[0];
  80384. if (mesh && wm) {
  80385. tmat.copyFrom(this.getAbsoluteTransform());
  80386. tmat.multiplyToRef(wm, tmat);
  80387. }
  80388. else {
  80389. tmat = this.getAbsoluteTransform();
  80390. }
  80391. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80392. };
  80393. /**
  80394. * Get the local position of a point that is in world space
  80395. * @param position The world position
  80396. * @param mesh The mesh that this bone is attached to
  80397. * @returns The local position
  80398. */
  80399. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80400. if (mesh === void 0) { mesh = null; }
  80401. var result = BABYLON.Vector3.Zero();
  80402. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80403. return result;
  80404. };
  80405. /**
  80406. * Get the local position of a point that is in world space and copy it to the result param
  80407. * @param position The world position
  80408. * @param mesh The mesh that this bone is attached to
  80409. * @param result The vector3 that the local position should be copied to
  80410. */
  80411. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80412. if (mesh === void 0) { mesh = null; }
  80413. var wm = null;
  80414. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80415. if (mesh) {
  80416. wm = mesh.getWorldMatrix();
  80417. }
  80418. this._skeleton.computeAbsoluteTransforms();
  80419. var tmat = Bone._tmpMats[0];
  80420. tmat.copyFrom(this.getAbsoluteTransform());
  80421. if (mesh && wm) {
  80422. tmat.multiplyToRef(wm, tmat);
  80423. }
  80424. tmat.invert();
  80425. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80426. };
  80427. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80428. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80429. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80430. return Bone;
  80431. }(BABYLON.Node));
  80432. BABYLON.Bone = Bone;
  80433. })(BABYLON || (BABYLON = {}));
  80434. //# sourceMappingURL=babylon.bone.js.map
  80435. var BABYLON;
  80436. (function (BABYLON) {
  80437. /**
  80438. * Class used to apply inverse kinematics to bones
  80439. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80440. */
  80441. var BoneIKController = /** @class */ (function () {
  80442. /**
  80443. * Creates a new BoneIKController
  80444. * @param mesh defines the mesh to control
  80445. * @param bone defines the bone to control
  80446. * @param options defines options to set up the controller
  80447. */
  80448. function BoneIKController(mesh, bone, options) {
  80449. /**
  80450. * Gets or sets the target position
  80451. */
  80452. this.targetPosition = BABYLON.Vector3.Zero();
  80453. /**
  80454. * Gets or sets the pole target position
  80455. */
  80456. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80457. /**
  80458. * Gets or sets the pole target local offset
  80459. */
  80460. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80461. /**
  80462. * Gets or sets the pole angle
  80463. */
  80464. this.poleAngle = 0;
  80465. /**
  80466. * 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)
  80467. */
  80468. this.slerpAmount = 1;
  80469. this._bone1Quat = BABYLON.Quaternion.Identity();
  80470. this._bone1Mat = BABYLON.Matrix.Identity();
  80471. this._bone2Ang = Math.PI;
  80472. this._maxAngle = Math.PI;
  80473. this._rightHandedSystem = false;
  80474. this._bendAxis = BABYLON.Vector3.Right();
  80475. this._slerping = false;
  80476. this._adjustRoll = 0;
  80477. this._bone2 = bone;
  80478. this._bone1 = bone.getParent();
  80479. if (!this._bone1) {
  80480. return;
  80481. }
  80482. this.mesh = mesh;
  80483. var bonePos = bone.getPosition();
  80484. if (bone.getAbsoluteTransform().determinant() > 0) {
  80485. this._rightHandedSystem = true;
  80486. this._bendAxis.x = 0;
  80487. this._bendAxis.y = 0;
  80488. this._bendAxis.z = -1;
  80489. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80490. this._adjustRoll = Math.PI * .5;
  80491. this._bendAxis.z = 1;
  80492. }
  80493. }
  80494. if (this._bone1.length) {
  80495. var boneScale1 = this._bone1.getScale();
  80496. var boneScale2 = this._bone2.getScale();
  80497. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80498. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80499. }
  80500. else if (this._bone1.children[0]) {
  80501. mesh.computeWorldMatrix(true);
  80502. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80503. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80504. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80505. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80506. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80507. }
  80508. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80509. this.maxAngle = Math.PI;
  80510. if (options) {
  80511. if (options.targetMesh) {
  80512. this.targetMesh = options.targetMesh;
  80513. this.targetMesh.computeWorldMatrix(true);
  80514. }
  80515. if (options.poleTargetMesh) {
  80516. this.poleTargetMesh = options.poleTargetMesh;
  80517. this.poleTargetMesh.computeWorldMatrix(true);
  80518. }
  80519. else if (options.poleTargetBone) {
  80520. this.poleTargetBone = options.poleTargetBone;
  80521. }
  80522. else if (this._bone1.getParent()) {
  80523. this.poleTargetBone = this._bone1.getParent();
  80524. }
  80525. if (options.poleTargetLocalOffset) {
  80526. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80527. }
  80528. if (options.poleAngle) {
  80529. this.poleAngle = options.poleAngle;
  80530. }
  80531. if (options.bendAxis) {
  80532. this._bendAxis.copyFrom(options.bendAxis);
  80533. }
  80534. if (options.maxAngle) {
  80535. this.maxAngle = options.maxAngle;
  80536. }
  80537. if (options.slerpAmount) {
  80538. this.slerpAmount = options.slerpAmount;
  80539. }
  80540. }
  80541. }
  80542. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80543. /**
  80544. * Gets or sets maximum allowed angle
  80545. */
  80546. get: function () {
  80547. return this._maxAngle;
  80548. },
  80549. set: function (value) {
  80550. this._setMaxAngle(value);
  80551. },
  80552. enumerable: true,
  80553. configurable: true
  80554. });
  80555. BoneIKController.prototype._setMaxAngle = function (ang) {
  80556. if (ang < 0) {
  80557. ang = 0;
  80558. }
  80559. if (ang > Math.PI || ang == undefined) {
  80560. ang = Math.PI;
  80561. }
  80562. this._maxAngle = ang;
  80563. var a = this._bone1Length;
  80564. var b = this._bone2Length;
  80565. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80566. };
  80567. /**
  80568. * Force the controller to update the bones
  80569. */
  80570. BoneIKController.prototype.update = function () {
  80571. var bone1 = this._bone1;
  80572. if (!bone1) {
  80573. return;
  80574. }
  80575. var target = this.targetPosition;
  80576. var poleTarget = this.poleTargetPosition;
  80577. var mat1 = BoneIKController._tmpMats[0];
  80578. var mat2 = BoneIKController._tmpMats[1];
  80579. if (this.targetMesh) {
  80580. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80581. }
  80582. if (this.poleTargetBone) {
  80583. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80584. }
  80585. else if (this.poleTargetMesh) {
  80586. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80587. }
  80588. var bonePos = BoneIKController._tmpVecs[0];
  80589. var zaxis = BoneIKController._tmpVecs[1];
  80590. var xaxis = BoneIKController._tmpVecs[2];
  80591. var yaxis = BoneIKController._tmpVecs[3];
  80592. var upAxis = BoneIKController._tmpVecs[4];
  80593. var _tmpQuat = BoneIKController._tmpQuat;
  80594. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80595. poleTarget.subtractToRef(bonePos, upAxis);
  80596. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80597. upAxis.y = 1;
  80598. }
  80599. else {
  80600. upAxis.normalize();
  80601. }
  80602. target.subtractToRef(bonePos, yaxis);
  80603. yaxis.normalize();
  80604. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80605. zaxis.normalize();
  80606. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80607. xaxis.normalize();
  80608. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80609. var a = this._bone1Length;
  80610. var b = this._bone2Length;
  80611. var c = BABYLON.Vector3.Distance(bonePos, target);
  80612. if (this._maxReach > 0) {
  80613. c = Math.min(this._maxReach, c);
  80614. }
  80615. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80616. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80617. if (acosa > 1) {
  80618. acosa = 1;
  80619. }
  80620. if (acosb > 1) {
  80621. acosb = 1;
  80622. }
  80623. if (acosa < -1) {
  80624. acosa = -1;
  80625. }
  80626. if (acosb < -1) {
  80627. acosb = -1;
  80628. }
  80629. var angA = Math.acos(acosa);
  80630. var angB = Math.acos(acosb);
  80631. var angC = -angA - angB;
  80632. if (this._rightHandedSystem) {
  80633. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80634. mat2.multiplyToRef(mat1, mat1);
  80635. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80636. mat2.multiplyToRef(mat1, mat1);
  80637. }
  80638. else {
  80639. var _tmpVec = BoneIKController._tmpVecs[5];
  80640. _tmpVec.copyFrom(this._bendAxis);
  80641. _tmpVec.x *= -1;
  80642. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80643. mat2.multiplyToRef(mat1, mat1);
  80644. }
  80645. if (this.poleAngle) {
  80646. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80647. mat1.multiplyToRef(mat2, mat1);
  80648. }
  80649. if (this._bone1) {
  80650. if (this.slerpAmount < 1) {
  80651. if (!this._slerping) {
  80652. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80653. }
  80654. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80655. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80656. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80657. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80658. this._slerping = true;
  80659. }
  80660. else {
  80661. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80662. this._bone1Mat.copyFrom(mat1);
  80663. this._slerping = false;
  80664. }
  80665. }
  80666. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80667. this._bone2Ang = angC;
  80668. };
  80669. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80670. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80671. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80672. return BoneIKController;
  80673. }());
  80674. BABYLON.BoneIKController = BoneIKController;
  80675. })(BABYLON || (BABYLON = {}));
  80676. //# sourceMappingURL=babylon.boneIKController.js.map
  80677. var BABYLON;
  80678. (function (BABYLON) {
  80679. /**
  80680. * Class used to make a bone look toward a point in space
  80681. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80682. */
  80683. var BoneLookController = /** @class */ (function () {
  80684. /**
  80685. * Create a BoneLookController
  80686. * @param mesh the mesh that the bone belongs to
  80687. * @param bone the bone that will be looking to the target
  80688. * @param target the target Vector3 to look at
  80689. * @param settings optional settings:
  80690. * * maxYaw: the maximum angle the bone will yaw to
  80691. * * minYaw: the minimum angle the bone will yaw to
  80692. * * maxPitch: the maximum angle the bone will pitch to
  80693. * * minPitch: the minimum angle the bone will yaw to
  80694. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80695. * * upAxis: the up axis of the coordinate system
  80696. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80697. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80698. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80699. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80700. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80701. * * adjustRoll: used to make an adjustment to the roll of the bone
  80702. **/
  80703. function BoneLookController(mesh, bone, target, options) {
  80704. /**
  80705. * The up axis of the coordinate system that is used when the bone is rotated
  80706. */
  80707. this.upAxis = BABYLON.Vector3.Up();
  80708. /**
  80709. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80710. */
  80711. this.upAxisSpace = BABYLON.Space.LOCAL;
  80712. /**
  80713. * Used to make an adjustment to the yaw of the bone
  80714. */
  80715. this.adjustYaw = 0;
  80716. /**
  80717. * Used to make an adjustment to the pitch of the bone
  80718. */
  80719. this.adjustPitch = 0;
  80720. /**
  80721. * Used to make an adjustment to the roll of the bone
  80722. */
  80723. this.adjustRoll = 0;
  80724. /**
  80725. * 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)
  80726. */
  80727. this.slerpAmount = 1;
  80728. this._boneQuat = BABYLON.Quaternion.Identity();
  80729. this._slerping = false;
  80730. this._firstFrameSkipped = false;
  80731. this._fowardAxis = BABYLON.Vector3.Forward();
  80732. this.mesh = mesh;
  80733. this.bone = bone;
  80734. this.target = target;
  80735. if (options) {
  80736. if (options.adjustYaw) {
  80737. this.adjustYaw = options.adjustYaw;
  80738. }
  80739. if (options.adjustPitch) {
  80740. this.adjustPitch = options.adjustPitch;
  80741. }
  80742. if (options.adjustRoll) {
  80743. this.adjustRoll = options.adjustRoll;
  80744. }
  80745. if (options.maxYaw != null) {
  80746. this.maxYaw = options.maxYaw;
  80747. }
  80748. else {
  80749. this.maxYaw = Math.PI;
  80750. }
  80751. if (options.minYaw != null) {
  80752. this.minYaw = options.minYaw;
  80753. }
  80754. else {
  80755. this.minYaw = -Math.PI;
  80756. }
  80757. if (options.maxPitch != null) {
  80758. this.maxPitch = options.maxPitch;
  80759. }
  80760. else {
  80761. this.maxPitch = Math.PI;
  80762. }
  80763. if (options.minPitch != null) {
  80764. this.minPitch = options.minPitch;
  80765. }
  80766. else {
  80767. this.minPitch = -Math.PI;
  80768. }
  80769. if (options.slerpAmount != null) {
  80770. this.slerpAmount = options.slerpAmount;
  80771. }
  80772. if (options.upAxis != null) {
  80773. this.upAxis = options.upAxis;
  80774. }
  80775. if (options.upAxisSpace != null) {
  80776. this.upAxisSpace = options.upAxisSpace;
  80777. }
  80778. if (options.yawAxis != null || options.pitchAxis != null) {
  80779. var newYawAxis = BABYLON.Axis.Y;
  80780. var newPitchAxis = BABYLON.Axis.X;
  80781. if (options.yawAxis != null) {
  80782. newYawAxis = options.yawAxis.clone();
  80783. newYawAxis.normalize();
  80784. }
  80785. if (options.pitchAxis != null) {
  80786. newPitchAxis = options.pitchAxis.clone();
  80787. newPitchAxis.normalize();
  80788. }
  80789. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80790. this._transformYawPitch = BABYLON.Matrix.Identity();
  80791. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80792. this._transformYawPitchInv = this._transformYawPitch.clone();
  80793. this._transformYawPitch.invert();
  80794. }
  80795. }
  80796. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80797. this.upAxisSpace = BABYLON.Space.LOCAL;
  80798. }
  80799. }
  80800. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80801. /**
  80802. * Gets or sets the minimum yaw angle that the bone can look to
  80803. */
  80804. get: function () {
  80805. return this._minYaw;
  80806. },
  80807. set: function (value) {
  80808. this._minYaw = value;
  80809. this._minYawSin = Math.sin(value);
  80810. this._minYawCos = Math.cos(value);
  80811. if (this._maxYaw != null) {
  80812. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80813. this._yawRange = this._maxYaw - this._minYaw;
  80814. }
  80815. },
  80816. enumerable: true,
  80817. configurable: true
  80818. });
  80819. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80820. /**
  80821. * Gets or sets the maximum yaw angle that the bone can look to
  80822. */
  80823. get: function () {
  80824. return this._maxYaw;
  80825. },
  80826. set: function (value) {
  80827. this._maxYaw = value;
  80828. this._maxYawSin = Math.sin(value);
  80829. this._maxYawCos = Math.cos(value);
  80830. if (this._minYaw != null) {
  80831. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80832. this._yawRange = this._maxYaw - this._minYaw;
  80833. }
  80834. },
  80835. enumerable: true,
  80836. configurable: true
  80837. });
  80838. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80839. /**
  80840. * Gets or sets the minimum pitch angle that the bone can look to
  80841. */
  80842. get: function () {
  80843. return this._minPitch;
  80844. },
  80845. set: function (value) {
  80846. this._minPitch = value;
  80847. this._minPitchTan = Math.tan(value);
  80848. },
  80849. enumerable: true,
  80850. configurable: true
  80851. });
  80852. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80853. /**
  80854. * Gets or sets the maximum pitch angle that the bone can look to
  80855. */
  80856. get: function () {
  80857. return this._maxPitch;
  80858. },
  80859. set: function (value) {
  80860. this._maxPitch = value;
  80861. this._maxPitchTan = Math.tan(value);
  80862. },
  80863. enumerable: true,
  80864. configurable: true
  80865. });
  80866. /**
  80867. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80868. */
  80869. BoneLookController.prototype.update = function () {
  80870. //skip the first frame when slerping so that the mesh rotation is correct
  80871. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80872. this._firstFrameSkipped = true;
  80873. return;
  80874. }
  80875. var bone = this.bone;
  80876. var bonePos = BoneLookController._tmpVecs[0];
  80877. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80878. var target = this.target;
  80879. var _tmpMat1 = BoneLookController._tmpMats[0];
  80880. var _tmpMat2 = BoneLookController._tmpMats[1];
  80881. var mesh = this.mesh;
  80882. var parentBone = bone.getParent();
  80883. var upAxis = BoneLookController._tmpVecs[1];
  80884. upAxis.copyFrom(this.upAxis);
  80885. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80886. if (this._transformYawPitch) {
  80887. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80888. }
  80889. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80890. }
  80891. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80892. mesh.getDirectionToRef(upAxis, upAxis);
  80893. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80894. upAxis.normalize();
  80895. }
  80896. }
  80897. var checkYaw = false;
  80898. var checkPitch = false;
  80899. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80900. checkYaw = true;
  80901. }
  80902. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80903. checkPitch = true;
  80904. }
  80905. if (checkYaw || checkPitch) {
  80906. var spaceMat = BoneLookController._tmpMats[2];
  80907. var spaceMatInv = BoneLookController._tmpMats[3];
  80908. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80909. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80910. }
  80911. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80912. spaceMat.copyFrom(mesh.getWorldMatrix());
  80913. }
  80914. else {
  80915. var forwardAxis = BoneLookController._tmpVecs[2];
  80916. forwardAxis.copyFrom(this._fowardAxis);
  80917. if (this._transformYawPitch) {
  80918. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80919. }
  80920. if (parentBone) {
  80921. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80922. }
  80923. else {
  80924. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80925. }
  80926. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80927. rightAxis.normalize();
  80928. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80929. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80930. }
  80931. spaceMat.invertToRef(spaceMatInv);
  80932. var xzlen = null;
  80933. if (checkPitch) {
  80934. var localTarget = BoneLookController._tmpVecs[3];
  80935. target.subtractToRef(bonePos, localTarget);
  80936. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80937. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80938. var pitch = Math.atan2(localTarget.y, xzlen);
  80939. var newPitch = pitch;
  80940. if (pitch > this._maxPitch) {
  80941. localTarget.y = this._maxPitchTan * xzlen;
  80942. newPitch = this._maxPitch;
  80943. }
  80944. else if (pitch < this._minPitch) {
  80945. localTarget.y = this._minPitchTan * xzlen;
  80946. newPitch = this._minPitch;
  80947. }
  80948. if (pitch != newPitch) {
  80949. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80950. localTarget.addInPlace(bonePos);
  80951. target = localTarget;
  80952. }
  80953. }
  80954. if (checkYaw) {
  80955. var localTarget = BoneLookController._tmpVecs[4];
  80956. target.subtractToRef(bonePos, localTarget);
  80957. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80958. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80959. var newYaw = yaw;
  80960. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80961. if (xzlen == null) {
  80962. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80963. }
  80964. if (this._yawRange > Math.PI) {
  80965. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80966. localTarget.z = this._maxYawCos * xzlen;
  80967. localTarget.x = this._maxYawSin * xzlen;
  80968. newYaw = this._maxYaw;
  80969. }
  80970. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80971. localTarget.z = this._minYawCos * xzlen;
  80972. localTarget.x = this._minYawSin * xzlen;
  80973. newYaw = this._minYaw;
  80974. }
  80975. }
  80976. else {
  80977. if (yaw > this._maxYaw) {
  80978. localTarget.z = this._maxYawCos * xzlen;
  80979. localTarget.x = this._maxYawSin * xzlen;
  80980. newYaw = this._maxYaw;
  80981. }
  80982. else if (yaw < this._minYaw) {
  80983. localTarget.z = this._minYawCos * xzlen;
  80984. localTarget.x = this._minYawSin * xzlen;
  80985. newYaw = this._minYaw;
  80986. }
  80987. }
  80988. }
  80989. if (this._slerping && this._yawRange > Math.PI) {
  80990. //are we going to be crossing into the min/max region?
  80991. var boneFwd = BoneLookController._tmpVecs[8];
  80992. boneFwd.copyFrom(BABYLON.Axis.Z);
  80993. if (this._transformYawPitch) {
  80994. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  80995. }
  80996. var boneRotMat = BoneLookController._tmpMats[4];
  80997. this._boneQuat.toRotationMatrix(boneRotMat);
  80998. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  80999. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  81000. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  81001. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  81002. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  81003. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  81004. if (angBtwTar > angBtwMidYaw) {
  81005. if (xzlen == null) {
  81006. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81007. }
  81008. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  81009. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  81010. if (angBtwMin < angBtwMax) {
  81011. newYaw = boneYaw + Math.PI * .75;
  81012. localTarget.z = Math.cos(newYaw) * xzlen;
  81013. localTarget.x = Math.sin(newYaw) * xzlen;
  81014. }
  81015. else {
  81016. newYaw = boneYaw - Math.PI * .75;
  81017. localTarget.z = Math.cos(newYaw) * xzlen;
  81018. localTarget.x = Math.sin(newYaw) * xzlen;
  81019. }
  81020. }
  81021. }
  81022. if (yaw != newYaw) {
  81023. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81024. localTarget.addInPlace(bonePos);
  81025. target = localTarget;
  81026. }
  81027. }
  81028. }
  81029. var zaxis = BoneLookController._tmpVecs[5];
  81030. var xaxis = BoneLookController._tmpVecs[6];
  81031. var yaxis = BoneLookController._tmpVecs[7];
  81032. var _tmpQuat = BoneLookController._tmpQuat;
  81033. target.subtractToRef(bonePos, zaxis);
  81034. zaxis.normalize();
  81035. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  81036. xaxis.normalize();
  81037. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  81038. yaxis.normalize();
  81039. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  81040. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  81041. return;
  81042. }
  81043. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  81044. return;
  81045. }
  81046. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  81047. return;
  81048. }
  81049. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  81050. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  81051. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  81052. }
  81053. if (this.slerpAmount < 1) {
  81054. if (!this._slerping) {
  81055. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  81056. }
  81057. if (this._transformYawPitch) {
  81058. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81059. }
  81060. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  81061. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  81062. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  81063. this._slerping = true;
  81064. }
  81065. else {
  81066. if (this._transformYawPitch) {
  81067. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81068. }
  81069. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  81070. this._slerping = false;
  81071. }
  81072. };
  81073. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  81074. var angDiff = ang2 - ang1;
  81075. angDiff %= Math.PI * 2;
  81076. if (angDiff > Math.PI) {
  81077. angDiff -= Math.PI * 2;
  81078. }
  81079. else if (angDiff < -Math.PI) {
  81080. angDiff += Math.PI * 2;
  81081. }
  81082. return angDiff;
  81083. };
  81084. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  81085. ang1 %= (2 * Math.PI);
  81086. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81087. ang2 %= (2 * Math.PI);
  81088. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81089. var ab = 0;
  81090. if (ang1 < ang2) {
  81091. ab = ang2 - ang1;
  81092. }
  81093. else {
  81094. ab = ang1 - ang2;
  81095. }
  81096. if (ab > Math.PI) {
  81097. ab = Math.PI * 2 - ab;
  81098. }
  81099. return ab;
  81100. };
  81101. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  81102. ang %= (2 * Math.PI);
  81103. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  81104. ang1 %= (2 * Math.PI);
  81105. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81106. ang2 %= (2 * Math.PI);
  81107. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81108. if (ang1 < ang2) {
  81109. if (ang > ang1 && ang < ang2) {
  81110. return true;
  81111. }
  81112. }
  81113. else {
  81114. if (ang > ang2 && ang < ang1) {
  81115. return true;
  81116. }
  81117. }
  81118. return false;
  81119. };
  81120. 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()];
  81121. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  81122. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81123. return BoneLookController;
  81124. }());
  81125. BABYLON.BoneLookController = BoneLookController;
  81126. })(BABYLON || (BABYLON = {}));
  81127. //# sourceMappingURL=babylon.boneLookController.js.map
  81128. var BABYLON;
  81129. (function (BABYLON) {
  81130. /**
  81131. * Class used to handle skinning animations
  81132. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81133. */
  81134. var Skeleton = /** @class */ (function () {
  81135. /**
  81136. * Creates a new skeleton
  81137. * @param name defines the skeleton name
  81138. * @param id defines the skeleton Id
  81139. * @param scene defines the hosting scene
  81140. */
  81141. function Skeleton(
  81142. /** defines the skeleton name */
  81143. name,
  81144. /** defines the skeleton Id */
  81145. id, scene) {
  81146. this.name = name;
  81147. this.id = id;
  81148. /**
  81149. * Gets the list of child bones
  81150. */
  81151. this.bones = new Array();
  81152. /**
  81153. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  81154. */
  81155. this.needInitialSkinMatrix = false;
  81156. this._isDirty = true;
  81157. this._meshesWithPoseMatrix = new Array();
  81158. this._identity = BABYLON.Matrix.Identity();
  81159. this._ranges = {};
  81160. this._lastAbsoluteTransformsUpdateId = -1;
  81161. /**
  81162. * Specifies if the skeleton should be serialized
  81163. */
  81164. this.doNotSerialize = false;
  81165. this._animationPropertiesOverride = null;
  81166. // Events
  81167. /**
  81168. * An observable triggered before computing the skeleton's matrices
  81169. */
  81170. this.onBeforeComputeObservable = new BABYLON.Observable();
  81171. this.bones = [];
  81172. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81173. scene.skeletons.push(this);
  81174. //make sure it will recalculate the matrix next time prepare is called.
  81175. this._isDirty = true;
  81176. }
  81177. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  81178. /**
  81179. * Gets or sets the animation properties override
  81180. */
  81181. get: function () {
  81182. if (!this._animationPropertiesOverride) {
  81183. return this._scene.animationPropertiesOverride;
  81184. }
  81185. return this._animationPropertiesOverride;
  81186. },
  81187. set: function (value) {
  81188. this._animationPropertiesOverride = value;
  81189. },
  81190. enumerable: true,
  81191. configurable: true
  81192. });
  81193. // Members
  81194. /**
  81195. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  81196. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  81197. * @returns a Float32Array containing matrices data
  81198. */
  81199. Skeleton.prototype.getTransformMatrices = function (mesh) {
  81200. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  81201. return mesh._bonesTransformMatrices;
  81202. }
  81203. if (!this._transformMatrices) {
  81204. this.prepare();
  81205. }
  81206. return this._transformMatrices;
  81207. };
  81208. /**
  81209. * Gets the current hosting scene
  81210. * @returns a scene object
  81211. */
  81212. Skeleton.prototype.getScene = function () {
  81213. return this._scene;
  81214. };
  81215. // Methods
  81216. /**
  81217. * Gets a string representing the current skeleton data
  81218. * @param fullDetails defines a boolean indicating if we want a verbose version
  81219. * @returns a string representing the current skeleton data
  81220. */
  81221. Skeleton.prototype.toString = function (fullDetails) {
  81222. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81223. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81224. if (fullDetails) {
  81225. ret += ", Ranges: {";
  81226. var first = true;
  81227. for (var name_1 in this._ranges) {
  81228. if (first) {
  81229. ret += ", ";
  81230. first = false;
  81231. }
  81232. ret += name_1;
  81233. }
  81234. ret += "}";
  81235. }
  81236. return ret;
  81237. };
  81238. /**
  81239. * Get bone's index searching by name
  81240. * @param name defines bone's name to search for
  81241. * @return the indice of the bone. Returns -1 if not found
  81242. */
  81243. Skeleton.prototype.getBoneIndexByName = function (name) {
  81244. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81245. if (this.bones[boneIndex].name === name) {
  81246. return boneIndex;
  81247. }
  81248. }
  81249. return -1;
  81250. };
  81251. /**
  81252. * Creater a new animation range
  81253. * @param name defines the name of the range
  81254. * @param from defines the start key
  81255. * @param to defines the end key
  81256. */
  81257. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81258. // check name not already in use
  81259. if (!this._ranges[name]) {
  81260. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81261. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81262. if (this.bones[i].animations[0]) {
  81263. this.bones[i].animations[0].createRange(name, from, to);
  81264. }
  81265. }
  81266. }
  81267. };
  81268. /**
  81269. * Delete a specific animation range
  81270. * @param name defines the name of the range
  81271. * @param deleteFrames defines if frames must be removed as well
  81272. */
  81273. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81274. if (deleteFrames === void 0) { deleteFrames = true; }
  81275. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81276. if (this.bones[i].animations[0]) {
  81277. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81278. }
  81279. }
  81280. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81281. };
  81282. /**
  81283. * Gets a specific animation range
  81284. * @param name defines the name of the range to look for
  81285. * @returns the requested animation range or null if not found
  81286. */
  81287. Skeleton.prototype.getAnimationRange = function (name) {
  81288. return this._ranges[name];
  81289. };
  81290. /**
  81291. * Gets the list of all animation ranges defined on this skeleton
  81292. * @returns an array
  81293. */
  81294. Skeleton.prototype.getAnimationRanges = function () {
  81295. var animationRanges = [];
  81296. var name;
  81297. var i = 0;
  81298. for (name in this._ranges) {
  81299. animationRanges[i] = this._ranges[name];
  81300. i++;
  81301. }
  81302. return animationRanges;
  81303. };
  81304. /**
  81305. * Copy animation range from a source skeleton.
  81306. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81307. * @param source defines the source skeleton
  81308. * @param name defines the name of the range to copy
  81309. * @param rescaleAsRequired defines if rescaling must be applied if required
  81310. * @returns true if operation was successful
  81311. */
  81312. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81313. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81314. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81315. return false;
  81316. }
  81317. var ret = true;
  81318. var frameOffset = this._getHighestAnimationFrame() + 1;
  81319. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81320. var boneDict = {};
  81321. var sourceBones = source.bones;
  81322. var nBones;
  81323. var i;
  81324. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81325. boneDict[sourceBones[i].name] = sourceBones[i];
  81326. }
  81327. if (this.bones.length !== sourceBones.length) {
  81328. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81329. ret = false;
  81330. }
  81331. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81332. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81333. var boneName = this.bones[i].name;
  81334. var sourceBone = boneDict[boneName];
  81335. if (sourceBone) {
  81336. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81337. }
  81338. else {
  81339. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81340. ret = false;
  81341. }
  81342. }
  81343. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81344. var range = source.getAnimationRange(name);
  81345. if (range) {
  81346. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81347. }
  81348. return ret;
  81349. };
  81350. /**
  81351. * Forces the skeleton to go to rest pose
  81352. */
  81353. Skeleton.prototype.returnToRest = function () {
  81354. for (var index = 0; index < this.bones.length; index++) {
  81355. this.bones[index].returnToRest();
  81356. }
  81357. };
  81358. Skeleton.prototype._getHighestAnimationFrame = function () {
  81359. var ret = 0;
  81360. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81361. if (this.bones[i].animations[0]) {
  81362. var highest = this.bones[i].animations[0].getHighestFrame();
  81363. if (ret < highest) {
  81364. ret = highest;
  81365. }
  81366. }
  81367. }
  81368. return ret;
  81369. };
  81370. /**
  81371. * Begin a specific animation range
  81372. * @param name defines the name of the range to start
  81373. * @param loop defines if looping must be turned on (false by default)
  81374. * @param speedRatio defines the speed ratio to apply (1 by default)
  81375. * @param onAnimationEnd defines a callback which will be called when animation will end
  81376. * @returns a new animatable
  81377. */
  81378. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81379. var range = this.getAnimationRange(name);
  81380. if (!range) {
  81381. return null;
  81382. }
  81383. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81384. };
  81385. /** @hidden */
  81386. Skeleton.prototype._markAsDirty = function () {
  81387. this._isDirty = true;
  81388. };
  81389. /** @hidden */
  81390. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81391. this._meshesWithPoseMatrix.push(mesh);
  81392. };
  81393. /** @hidden */
  81394. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81395. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81396. if (index > -1) {
  81397. this._meshesWithPoseMatrix.splice(index, 1);
  81398. }
  81399. };
  81400. /** @hidden */
  81401. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81402. this.onBeforeComputeObservable.notifyObservers(this);
  81403. for (var index = 0; index < this.bones.length; index++) {
  81404. var bone = this.bones[index];
  81405. var parentBone = bone.getParent();
  81406. if (parentBone) {
  81407. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81408. }
  81409. else {
  81410. if (initialSkinMatrix) {
  81411. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81412. }
  81413. else {
  81414. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81415. }
  81416. }
  81417. if (bone._index !== -1) {
  81418. var mappedIndex = bone._index === null ? index : bone._index;
  81419. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81420. }
  81421. }
  81422. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81423. };
  81424. /**
  81425. * Build all resources required to render a skeleton
  81426. */
  81427. Skeleton.prototype.prepare = function () {
  81428. if (!this._isDirty) {
  81429. return;
  81430. }
  81431. if (this.needInitialSkinMatrix) {
  81432. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81433. var mesh = this._meshesWithPoseMatrix[index];
  81434. var poseMatrix = mesh.getPoseMatrix();
  81435. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81436. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81437. }
  81438. if (this._synchronizedWithMesh !== mesh) {
  81439. this._synchronizedWithMesh = mesh;
  81440. // Prepare bones
  81441. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81442. var bone = this.bones[boneIndex];
  81443. if (!bone.getParent()) {
  81444. var matrix = bone.getBaseMatrix();
  81445. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81446. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81447. }
  81448. }
  81449. }
  81450. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81451. }
  81452. }
  81453. else {
  81454. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81455. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81456. }
  81457. this._computeTransformMatrices(this._transformMatrices, null);
  81458. }
  81459. this._isDirty = false;
  81460. this._scene._activeBones.addCount(this.bones.length, false);
  81461. };
  81462. /**
  81463. * Gets the list of animatables currently running for this skeleton
  81464. * @returns an array of animatables
  81465. */
  81466. Skeleton.prototype.getAnimatables = function () {
  81467. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81468. this._animatables = [];
  81469. for (var index = 0; index < this.bones.length; index++) {
  81470. this._animatables.push(this.bones[index]);
  81471. }
  81472. }
  81473. return this._animatables;
  81474. };
  81475. /**
  81476. * Clone the current skeleton
  81477. * @param name defines the name of the new skeleton
  81478. * @param id defines the id of the enw skeleton
  81479. * @returns the new skeleton
  81480. */
  81481. Skeleton.prototype.clone = function (name, id) {
  81482. var result = new Skeleton(name, id || name, this._scene);
  81483. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81484. for (var index = 0; index < this.bones.length; index++) {
  81485. var source = this.bones[index];
  81486. var parentBone = null;
  81487. var parent_1 = source.getParent();
  81488. if (parent_1) {
  81489. var parentIndex = this.bones.indexOf(parent_1);
  81490. parentBone = result.bones[parentIndex];
  81491. }
  81492. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81493. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81494. }
  81495. if (this._ranges) {
  81496. result._ranges = {};
  81497. for (var rangeName in this._ranges) {
  81498. var range = this._ranges[rangeName];
  81499. if (range) {
  81500. result._ranges[rangeName] = range.clone();
  81501. }
  81502. }
  81503. }
  81504. this._isDirty = true;
  81505. return result;
  81506. };
  81507. /**
  81508. * Enable animation blending for this skeleton
  81509. * @param blendingSpeed defines the blending speed to apply
  81510. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81511. */
  81512. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81513. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81514. this.bones.forEach(function (bone) {
  81515. bone.animations.forEach(function (animation) {
  81516. animation.enableBlending = true;
  81517. animation.blendingSpeed = blendingSpeed;
  81518. });
  81519. });
  81520. };
  81521. /**
  81522. * Releases all resources associated with the current skeleton
  81523. */
  81524. Skeleton.prototype.dispose = function () {
  81525. this._meshesWithPoseMatrix = [];
  81526. // Animations
  81527. this.getScene().stopAnimation(this);
  81528. // Remove from scene
  81529. this.getScene().removeSkeleton(this);
  81530. };
  81531. /**
  81532. * Serialize the skeleton in a JSON object
  81533. * @returns a JSON object
  81534. */
  81535. Skeleton.prototype.serialize = function () {
  81536. var serializationObject = {};
  81537. serializationObject.name = this.name;
  81538. serializationObject.id = this.id;
  81539. if (this.dimensionsAtRest) {
  81540. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81541. }
  81542. serializationObject.bones = [];
  81543. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81544. for (var index = 0; index < this.bones.length; index++) {
  81545. var bone = this.bones[index];
  81546. var parent_2 = bone.getParent();
  81547. var serializedBone = {
  81548. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81549. name: bone.name,
  81550. matrix: bone.getBaseMatrix().toArray(),
  81551. rest: bone.getRestPose().toArray()
  81552. };
  81553. serializationObject.bones.push(serializedBone);
  81554. if (bone.length) {
  81555. serializedBone.length = bone.length;
  81556. }
  81557. if (bone.metadata) {
  81558. serializedBone.metadata = bone.metadata;
  81559. }
  81560. if (bone.animations && bone.animations.length > 0) {
  81561. serializedBone.animation = bone.animations[0].serialize();
  81562. }
  81563. serializationObject.ranges = [];
  81564. for (var name in this._ranges) {
  81565. var source = this._ranges[name];
  81566. if (!source) {
  81567. continue;
  81568. }
  81569. var range = {};
  81570. range.name = name;
  81571. range.from = source.from;
  81572. range.to = source.to;
  81573. serializationObject.ranges.push(range);
  81574. }
  81575. }
  81576. return serializationObject;
  81577. };
  81578. /**
  81579. * Creates a new skeleton from serialized data
  81580. * @param parsedSkeleton defines the serialized data
  81581. * @param scene defines the hosting scene
  81582. * @returns a new skeleton
  81583. */
  81584. Skeleton.Parse = function (parsedSkeleton, scene) {
  81585. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81586. if (parsedSkeleton.dimensionsAtRest) {
  81587. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81588. }
  81589. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81590. var index;
  81591. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81592. var parsedBone = parsedSkeleton.bones[index];
  81593. var parentBone = null;
  81594. if (parsedBone.parentBoneIndex > -1) {
  81595. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81596. }
  81597. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81598. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81599. if (parsedBone.length) {
  81600. bone.length = parsedBone.length;
  81601. }
  81602. if (parsedBone.metadata) {
  81603. bone.metadata = parsedBone.metadata;
  81604. }
  81605. if (parsedBone.animation) {
  81606. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81607. }
  81608. }
  81609. // placed after bones, so createAnimationRange can cascade down
  81610. if (parsedSkeleton.ranges) {
  81611. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81612. var data = parsedSkeleton.ranges[index];
  81613. skeleton.createAnimationRange(data.name, data.from, data.to);
  81614. }
  81615. }
  81616. return skeleton;
  81617. };
  81618. /**
  81619. * Compute all node absolute transforms
  81620. * @param forceUpdate defines if computation must be done even if cache is up to date
  81621. */
  81622. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81623. if (forceUpdate === void 0) { forceUpdate = false; }
  81624. var renderId = this._scene.getRenderId();
  81625. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81626. this.bones[0].computeAbsoluteTransforms();
  81627. this._lastAbsoluteTransformsUpdateId = renderId;
  81628. }
  81629. };
  81630. /**
  81631. * Gets the root pose matrix
  81632. * @returns a matrix
  81633. */
  81634. Skeleton.prototype.getPoseMatrix = function () {
  81635. var poseMatrix = null;
  81636. if (this._meshesWithPoseMatrix.length > 0) {
  81637. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81638. }
  81639. return poseMatrix;
  81640. };
  81641. /**
  81642. * Sorts bones per internal index
  81643. */
  81644. Skeleton.prototype.sortBones = function () {
  81645. var bones = new Array();
  81646. var visited = new Array(this.bones.length);
  81647. for (var index = 0; index < this.bones.length; index++) {
  81648. this._sortBones(index, bones, visited);
  81649. }
  81650. this.bones = bones;
  81651. };
  81652. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81653. if (visited[index]) {
  81654. return;
  81655. }
  81656. visited[index] = true;
  81657. var bone = this.bones[index];
  81658. if (bone._index === undefined) {
  81659. bone._index = index;
  81660. }
  81661. var parentBone = bone.getParent();
  81662. if (parentBone) {
  81663. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81664. }
  81665. bones.push(bone);
  81666. };
  81667. return Skeleton;
  81668. }());
  81669. BABYLON.Skeleton = Skeleton;
  81670. })(BABYLON || (BABYLON = {}));
  81671. //# sourceMappingURL=babylon.skeleton.js.map
  81672. var BABYLON;
  81673. (function (BABYLON) {
  81674. var SphericalPolynomial = /** @class */ (function () {
  81675. function SphericalPolynomial() {
  81676. this.x = BABYLON.Vector3.Zero();
  81677. this.y = BABYLON.Vector3.Zero();
  81678. this.z = BABYLON.Vector3.Zero();
  81679. this.xx = BABYLON.Vector3.Zero();
  81680. this.yy = BABYLON.Vector3.Zero();
  81681. this.zz = BABYLON.Vector3.Zero();
  81682. this.xy = BABYLON.Vector3.Zero();
  81683. this.yz = BABYLON.Vector3.Zero();
  81684. this.zx = BABYLON.Vector3.Zero();
  81685. }
  81686. SphericalPolynomial.prototype.addAmbient = function (color) {
  81687. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81688. this.xx = this.xx.add(colorVector);
  81689. this.yy = this.yy.add(colorVector);
  81690. this.zz = this.zz.add(colorVector);
  81691. };
  81692. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  81693. var result = new SphericalPolynomial();
  81694. result.x = harmonics.L11.scale(1.02333);
  81695. result.y = harmonics.L1_1.scale(1.02333);
  81696. result.z = harmonics.L10.scale(1.02333);
  81697. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  81698. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  81699. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  81700. result.yz = harmonics.L2_1.scale(0.858086);
  81701. result.zx = harmonics.L21.scale(0.858086);
  81702. result.xy = harmonics.L2_2.scale(0.858086);
  81703. result.scale(1.0 / Math.PI);
  81704. return result;
  81705. };
  81706. SphericalPolynomial.prototype.scale = function (scale) {
  81707. this.x = this.x.scale(scale);
  81708. this.y = this.y.scale(scale);
  81709. this.z = this.z.scale(scale);
  81710. this.xx = this.xx.scale(scale);
  81711. this.yy = this.yy.scale(scale);
  81712. this.zz = this.zz.scale(scale);
  81713. this.yz = this.yz.scale(scale);
  81714. this.zx = this.zx.scale(scale);
  81715. this.xy = this.xy.scale(scale);
  81716. };
  81717. return SphericalPolynomial;
  81718. }());
  81719. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81720. var SphericalHarmonics = /** @class */ (function () {
  81721. function SphericalHarmonics() {
  81722. this.L00 = BABYLON.Vector3.Zero();
  81723. this.L1_1 = BABYLON.Vector3.Zero();
  81724. this.L10 = BABYLON.Vector3.Zero();
  81725. this.L11 = BABYLON.Vector3.Zero();
  81726. this.L2_2 = BABYLON.Vector3.Zero();
  81727. this.L2_1 = BABYLON.Vector3.Zero();
  81728. this.L20 = BABYLON.Vector3.Zero();
  81729. this.L21 = BABYLON.Vector3.Zero();
  81730. this.L22 = BABYLON.Vector3.Zero();
  81731. }
  81732. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81733. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81734. var c = colorVector.scale(deltaSolidAngle);
  81735. this.L00 = this.L00.add(c.scale(0.282095));
  81736. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  81737. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  81738. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  81739. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81740. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81741. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  81742. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81743. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81744. };
  81745. SphericalHarmonics.prototype.scale = function (scale) {
  81746. this.L00 = this.L00.scale(scale);
  81747. this.L1_1 = this.L1_1.scale(scale);
  81748. this.L10 = this.L10.scale(scale);
  81749. this.L11 = this.L11.scale(scale);
  81750. this.L2_2 = this.L2_2.scale(scale);
  81751. this.L2_1 = this.L2_1.scale(scale);
  81752. this.L20 = this.L20.scale(scale);
  81753. this.L21 = this.L21.scale(scale);
  81754. this.L22 = this.L22.scale(scale);
  81755. };
  81756. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81757. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81758. //
  81759. // E_lm = A_l * L_lm
  81760. //
  81761. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81762. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81763. // the scaling factors are given in equation 9.
  81764. // Constant (Band 0)
  81765. this.L00 = this.L00.scale(3.141593);
  81766. // Linear (Band 1)
  81767. this.L1_1 = this.L1_1.scale(2.094395);
  81768. this.L10 = this.L10.scale(2.094395);
  81769. this.L11 = this.L11.scale(2.094395);
  81770. // Quadratic (Band 2)
  81771. this.L2_2 = this.L2_2.scale(0.785398);
  81772. this.L2_1 = this.L2_1.scale(0.785398);
  81773. this.L20 = this.L20.scale(0.785398);
  81774. this.L21 = this.L21.scale(0.785398);
  81775. this.L22 = this.L22.scale(0.785398);
  81776. };
  81777. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81778. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81779. // L = (1/pi) * E * rho
  81780. //
  81781. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81782. this.scale(1.0 / Math.PI);
  81783. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81784. // (The pixel shader must apply albedo after texture fetches, etc).
  81785. };
  81786. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  81787. var result = new SphericalHarmonics();
  81788. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81789. result.L1_1 = polynomial.y.scale(0.977204);
  81790. result.L10 = polynomial.z.scale(0.977204);
  81791. result.L11 = polynomial.x.scale(0.977204);
  81792. result.L2_2 = polynomial.xy.scale(1.16538);
  81793. result.L2_1 = polynomial.yz.scale(1.16538);
  81794. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81795. result.L21 = polynomial.zx.scale(1.16538);
  81796. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81797. result.scale(Math.PI);
  81798. return result;
  81799. };
  81800. return SphericalHarmonics;
  81801. }());
  81802. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81803. })(BABYLON || (BABYLON = {}));
  81804. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81805. var BABYLON;
  81806. (function (BABYLON) {
  81807. var FileFaceOrientation = /** @class */ (function () {
  81808. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81809. this.name = name;
  81810. this.worldAxisForNormal = worldAxisForNormal;
  81811. this.worldAxisForFileX = worldAxisForFileX;
  81812. this.worldAxisForFileY = worldAxisForFileY;
  81813. }
  81814. return FileFaceOrientation;
  81815. }());
  81816. ;
  81817. /**
  81818. * Helper class dealing with the extraction of spherical polynomial dataArray
  81819. * from a cube map.
  81820. */
  81821. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81822. function CubeMapToSphericalPolynomialTools() {
  81823. }
  81824. /**
  81825. * Converts a texture to the according Spherical Polynomial data.
  81826. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81827. *
  81828. * @param texture The texture to extract the information from.
  81829. * @return The Spherical Polynomial data.
  81830. */
  81831. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81832. if (!texture.isCube) {
  81833. // Only supports cube Textures currently.
  81834. return null;
  81835. }
  81836. var size = texture.getSize().width;
  81837. var right = texture.readPixels(0);
  81838. var left = texture.readPixels(1);
  81839. var up;
  81840. var down;
  81841. if (texture.isRenderTarget) {
  81842. up = texture.readPixels(3);
  81843. down = texture.readPixels(2);
  81844. }
  81845. else {
  81846. up = texture.readPixels(2);
  81847. down = texture.readPixels(3);
  81848. }
  81849. var front = texture.readPixels(4);
  81850. var back = texture.readPixels(5);
  81851. var gammaSpace = texture.gammaSpace;
  81852. // Always read as RGBA.
  81853. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81854. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81855. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81856. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81857. }
  81858. var cubeInfo = {
  81859. size: size,
  81860. right: right,
  81861. left: left,
  81862. up: up,
  81863. down: down,
  81864. front: front,
  81865. back: back,
  81866. format: format,
  81867. type: type,
  81868. gammaSpace: gammaSpace,
  81869. };
  81870. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81871. };
  81872. /**
  81873. * Converts a cubemap to the according Spherical Polynomial data.
  81874. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81875. *
  81876. * @param cubeInfo The Cube map to extract the information from.
  81877. * @return The Spherical Polynomial data.
  81878. */
  81879. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81880. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81881. var totalSolidAngle = 0.0;
  81882. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81883. var du = 2.0 / cubeInfo.size;
  81884. var dv = du;
  81885. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81886. var minUV = du * 0.5 - 1.0;
  81887. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81888. var fileFace = this.FileFaces[faceIndex];
  81889. var dataArray = cubeInfo[fileFace.name];
  81890. var v = minUV;
  81891. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  81892. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  81893. // Because SP is still linear, so summation is fine in that basis.
  81894. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  81895. for (var y = 0; y < cubeInfo.size; y++) {
  81896. var u = minUV;
  81897. for (var x = 0; x < cubeInfo.size; x++) {
  81898. // World direction (not normalised)
  81899. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  81900. worldDirection.normalize();
  81901. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  81902. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  81903. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  81904. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  81905. // Handle Integer types.
  81906. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81907. r /= 255;
  81908. g /= 255;
  81909. b /= 255;
  81910. }
  81911. // Handle Gamma space textures.
  81912. if (cubeInfo.gammaSpace) {
  81913. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  81914. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  81915. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  81916. }
  81917. var color = new BABYLON.Color3(r, g, b);
  81918. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  81919. totalSolidAngle += deltaSolidAngle;
  81920. u += du;
  81921. }
  81922. v += dv;
  81923. }
  81924. }
  81925. // Solid angle for entire sphere is 4*pi
  81926. var sphereSolidAngle = 4.0 * Math.PI;
  81927. // Adjust the solid angle to allow for how many faces we processed.
  81928. var facesProcessed = 6.0;
  81929. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  81930. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  81931. // This is needed because the numerical integration over the cube uses a
  81932. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  81933. // and also to compensate for accumulative error due to float precision in the summation.
  81934. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  81935. sphericalHarmonics.scale(correctionFactor);
  81936. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  81937. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  81938. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  81939. };
  81940. CubeMapToSphericalPolynomialTools.FileFaces = [
  81941. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  81942. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  81943. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  81944. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  81945. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  81946. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  81947. ];
  81948. return CubeMapToSphericalPolynomialTools;
  81949. }());
  81950. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  81951. })(BABYLON || (BABYLON = {}));
  81952. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  81953. var BABYLON;
  81954. (function (BABYLON) {
  81955. /**
  81956. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  81957. */
  81958. var PanoramaToCubeMapTools = /** @class */ (function () {
  81959. function PanoramaToCubeMapTools() {
  81960. }
  81961. /**
  81962. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  81963. *
  81964. * @param float32Array The source data.
  81965. * @param inputWidth The width of the input panorama.
  81966. * @param inputhHeight The height of the input panorama.
  81967. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  81968. * @return The cubemap data
  81969. */
  81970. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  81971. if (!float32Array) {
  81972. throw "ConvertPanoramaToCubemap: input cannot be null";
  81973. }
  81974. if (float32Array.length != inputWidth * inputHeight * 3) {
  81975. throw "ConvertPanoramaToCubemap: input size is wrong";
  81976. }
  81977. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  81978. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  81979. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  81980. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  81981. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  81982. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  81983. return {
  81984. front: textureFront,
  81985. back: textureBack,
  81986. left: textureLeft,
  81987. right: textureRight,
  81988. up: textureUp,
  81989. down: textureDown,
  81990. size: size,
  81991. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  81992. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  81993. gammaSpace: false,
  81994. };
  81995. };
  81996. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  81997. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  81998. var textureArray = new Float32Array(buffer);
  81999. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  82000. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  82001. var dy = 1 / texSize;
  82002. var fy = 0;
  82003. for (var y = 0; y < texSize; y++) {
  82004. var xv1 = faceData[0];
  82005. var xv2 = faceData[2];
  82006. for (var x = 0; x < texSize; x++) {
  82007. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  82008. v.normalize();
  82009. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  82010. // 3 channels per pixels
  82011. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  82012. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  82013. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  82014. xv1 = xv1.add(rotDX1);
  82015. xv2 = xv2.add(rotDX2);
  82016. }
  82017. fy += dy;
  82018. }
  82019. return textureArray;
  82020. };
  82021. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  82022. var theta = Math.atan2(vDir.z, vDir.x);
  82023. var phi = Math.acos(vDir.y);
  82024. while (theta < -Math.PI)
  82025. theta += 2 * Math.PI;
  82026. while (theta > Math.PI)
  82027. theta -= 2 * Math.PI;
  82028. var dx = theta / Math.PI;
  82029. var dy = phi / Math.PI;
  82030. // recenter.
  82031. dx = dx * 0.5 + 0.5;
  82032. var px = Math.round(dx * inputWidth);
  82033. if (px < 0)
  82034. px = 0;
  82035. else if (px >= inputWidth)
  82036. px = inputWidth - 1;
  82037. var py = Math.round(dy * inputHeight);
  82038. if (py < 0)
  82039. py = 0;
  82040. else if (py >= inputHeight)
  82041. py = inputHeight - 1;
  82042. var inputY = (inputHeight - py - 1);
  82043. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  82044. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  82045. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  82046. return {
  82047. r: r,
  82048. g: g,
  82049. b: b
  82050. };
  82051. };
  82052. PanoramaToCubeMapTools.FACE_FRONT = [
  82053. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82054. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82055. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82056. new BABYLON.Vector3(1.0, 1.0, -1.0)
  82057. ];
  82058. PanoramaToCubeMapTools.FACE_BACK = [
  82059. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82060. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82061. new BABYLON.Vector3(1.0, 1.0, 1.0),
  82062. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  82063. ];
  82064. PanoramaToCubeMapTools.FACE_RIGHT = [
  82065. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82066. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82067. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82068. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82069. ];
  82070. PanoramaToCubeMapTools.FACE_LEFT = [
  82071. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82072. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82073. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82074. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  82075. ];
  82076. PanoramaToCubeMapTools.FACE_DOWN = [
  82077. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82078. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82079. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82080. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82081. ];
  82082. PanoramaToCubeMapTools.FACE_UP = [
  82083. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82084. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82085. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82086. new BABYLON.Vector3(1.0, -1.0, -1.0)
  82087. ];
  82088. return PanoramaToCubeMapTools;
  82089. }());
  82090. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  82091. })(BABYLON || (BABYLON = {}));
  82092. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  82093. var BABYLON;
  82094. (function (BABYLON) {
  82095. ;
  82096. /**
  82097. * This groups tools to convert HDR texture to native colors array.
  82098. */
  82099. var HDRTools = /** @class */ (function () {
  82100. function HDRTools() {
  82101. }
  82102. HDRTools.Ldexp = function (mantissa, exponent) {
  82103. if (exponent > 1023) {
  82104. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  82105. }
  82106. if (exponent < -1074) {
  82107. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  82108. }
  82109. return mantissa * Math.pow(2, exponent);
  82110. };
  82111. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  82112. if (exponent > 0) { /*nonzero pixel*/
  82113. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  82114. float32array[index + 0] = red * exponent;
  82115. float32array[index + 1] = green * exponent;
  82116. float32array[index + 2] = blue * exponent;
  82117. }
  82118. else {
  82119. float32array[index + 0] = 0;
  82120. float32array[index + 1] = 0;
  82121. float32array[index + 2] = 0;
  82122. }
  82123. };
  82124. HDRTools.readStringLine = function (uint8array, startIndex) {
  82125. var line = "";
  82126. var character = "";
  82127. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  82128. character = String.fromCharCode(uint8array[i]);
  82129. if (character == "\n") {
  82130. break;
  82131. }
  82132. line += character;
  82133. }
  82134. return line;
  82135. };
  82136. /**
  82137. * Reads header information from an RGBE texture stored in a native array.
  82138. * More information on this format are available here:
  82139. * https://en.wikipedia.org/wiki/RGBE_image_format
  82140. *
  82141. * @param uint8array The binary file stored in native array.
  82142. * @return The header information.
  82143. */
  82144. HDRTools.RGBE_ReadHeader = function (uint8array) {
  82145. var height = 0;
  82146. var width = 0;
  82147. var line = this.readStringLine(uint8array, 0);
  82148. if (line[0] != '#' || line[1] != '?') {
  82149. throw "Bad HDR Format.";
  82150. }
  82151. var endOfHeader = false;
  82152. var findFormat = false;
  82153. var lineIndex = 0;
  82154. do {
  82155. lineIndex += (line.length + 1);
  82156. line = this.readStringLine(uint8array, lineIndex);
  82157. if (line == "FORMAT=32-bit_rle_rgbe") {
  82158. findFormat = true;
  82159. }
  82160. else if (line.length == 0) {
  82161. endOfHeader = true;
  82162. }
  82163. } while (!endOfHeader);
  82164. if (!findFormat) {
  82165. throw "HDR Bad header format, unsupported FORMAT";
  82166. }
  82167. lineIndex += (line.length + 1);
  82168. line = this.readStringLine(uint8array, lineIndex);
  82169. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  82170. var match = sizeRegexp.exec(line);
  82171. // TODO. Support +Y and -X if needed.
  82172. if (!match || match.length < 3) {
  82173. throw "HDR Bad header format, no size";
  82174. }
  82175. width = parseInt(match[2]);
  82176. height = parseInt(match[1]);
  82177. if (width < 8 || width > 0x7fff) {
  82178. throw "HDR Bad header format, unsupported size";
  82179. }
  82180. lineIndex += (line.length + 1);
  82181. return {
  82182. height: height,
  82183. width: width,
  82184. dataPosition: lineIndex
  82185. };
  82186. };
  82187. /**
  82188. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  82189. * This RGBE texture needs to store the information as a panorama.
  82190. *
  82191. * More information on this format are available here:
  82192. * https://en.wikipedia.org/wiki/RGBE_image_format
  82193. *
  82194. * @param buffer The binary file stored in an array buffer.
  82195. * @param size The expected size of the extracted cubemap.
  82196. * @return The Cube Map information.
  82197. */
  82198. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  82199. var uint8array = new Uint8Array(buffer);
  82200. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  82201. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82202. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  82203. return cubeMapData;
  82204. };
  82205. /**
  82206. * Returns the pixels data extracted from an RGBE texture.
  82207. * This pixels will be stored left to right up to down in the R G B order in one array.
  82208. *
  82209. * More information on this format are available here:
  82210. * https://en.wikipedia.org/wiki/RGBE_image_format
  82211. *
  82212. * @param uint8array The binary file stored in an array buffer.
  82213. * @param hdrInfo The header information of the file.
  82214. * @return The pixels data in RGB right to left up to down order.
  82215. */
  82216. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82217. // Keep for multi format supports.
  82218. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82219. };
  82220. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82221. var num_scanlines = hdrInfo.height;
  82222. var scanline_width = hdrInfo.width;
  82223. var a, b, c, d, count;
  82224. var dataIndex = hdrInfo.dataPosition;
  82225. var index = 0, endIndex = 0, i = 0;
  82226. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82227. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82228. // 3 channels of 4 bytes per pixel in float.
  82229. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82230. var resultArray = new Float32Array(resultBuffer);
  82231. // read in each successive scanline
  82232. while (num_scanlines > 0) {
  82233. a = uint8array[dataIndex++];
  82234. b = uint8array[dataIndex++];
  82235. c = uint8array[dataIndex++];
  82236. d = uint8array[dataIndex++];
  82237. if (a != 2 || b != 2 || (c & 0x80)) {
  82238. // this file is not run length encoded
  82239. throw "HDR Bad header format, not RLE";
  82240. }
  82241. if (((c << 8) | d) != scanline_width) {
  82242. throw "HDR Bad header format, wrong scan line width";
  82243. }
  82244. index = 0;
  82245. // read each of the four channels for the scanline into the buffer
  82246. for (i = 0; i < 4; i++) {
  82247. endIndex = (i + 1) * scanline_width;
  82248. while (index < endIndex) {
  82249. a = uint8array[dataIndex++];
  82250. b = uint8array[dataIndex++];
  82251. if (a > 128) {
  82252. // a run of the same value
  82253. count = a - 128;
  82254. if ((count == 0) || (count > endIndex - index)) {
  82255. throw "HDR Bad Format, bad scanline data (run)";
  82256. }
  82257. while (count-- > 0) {
  82258. scanLineArray[index++] = b;
  82259. }
  82260. }
  82261. else {
  82262. // a non-run
  82263. count = a;
  82264. if ((count == 0) || (count > endIndex - index)) {
  82265. throw "HDR Bad Format, bad scanline data (non-run)";
  82266. }
  82267. scanLineArray[index++] = b;
  82268. if (--count > 0) {
  82269. for (var j = 0; j < count; j++) {
  82270. scanLineArray[index++] = uint8array[dataIndex++];
  82271. }
  82272. }
  82273. }
  82274. }
  82275. }
  82276. // now convert data from buffer into floats
  82277. for (i = 0; i < scanline_width; i++) {
  82278. a = scanLineArray[i];
  82279. b = scanLineArray[i + scanline_width];
  82280. c = scanLineArray[i + 2 * scanline_width];
  82281. d = scanLineArray[i + 3 * scanline_width];
  82282. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82283. }
  82284. num_scanlines--;
  82285. }
  82286. return resultArray;
  82287. };
  82288. return HDRTools;
  82289. }());
  82290. BABYLON.HDRTools = HDRTools;
  82291. })(BABYLON || (BABYLON = {}));
  82292. //# sourceMappingURL=babylon.hdr.js.map
  82293. var BABYLON;
  82294. (function (BABYLON) {
  82295. /**
  82296. * Sets of helpers addressing the serialization and deserialization of environment texture
  82297. * stored in a BabylonJS env file.
  82298. * Those files are usually stored as .env files.
  82299. */
  82300. var EnvironmentTextureTools = /** @class */ (function () {
  82301. function EnvironmentTextureTools() {
  82302. }
  82303. /**
  82304. * Gets the environment info from an env file.
  82305. * @param data The array buffer containing the .env bytes.
  82306. * @returns the environment file info (the json header) if successfully parsed.
  82307. */
  82308. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82309. var dataView = new DataView(data);
  82310. var pos = 0;
  82311. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82312. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82313. BABYLON.Tools.Error('Not a babylon environment map');
  82314. return null;
  82315. }
  82316. }
  82317. // Read json manifest - collect characters up to null terminator
  82318. var manifestString = '';
  82319. var charCode = 0x00;
  82320. while ((charCode = dataView.getUint8(pos++))) {
  82321. manifestString += String.fromCharCode(charCode);
  82322. }
  82323. var manifest = JSON.parse(manifestString);
  82324. if (manifest.specular) {
  82325. // Extend the header with the position of the payload.
  82326. manifest.specular.specularDataPosition = pos;
  82327. }
  82328. return manifest;
  82329. };
  82330. /**
  82331. * Creates an environment texture from a loaded cube texture.
  82332. * @param texture defines the cube texture to convert in env file
  82333. * @return a promise containing the environment data if succesfull.
  82334. */
  82335. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82336. var _this = this;
  82337. var internalTexture = texture.getInternalTexture();
  82338. if (!internalTexture) {
  82339. return Promise.reject("The cube texture is invalid.");
  82340. }
  82341. if (!texture._prefiltered) {
  82342. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82343. }
  82344. var engine = internalTexture.getEngine();
  82345. if (engine && engine.premultipliedAlpha) {
  82346. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82347. }
  82348. var canvas = engine.getRenderingCanvas();
  82349. if (!canvas) {
  82350. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82351. }
  82352. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82353. if (!engine.getCaps().textureFloatRender) {
  82354. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82355. if (!engine.getCaps().textureHalfFloatRender) {
  82356. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82357. }
  82358. }
  82359. var cubeWidth = internalTexture.width;
  82360. var hostingScene = new BABYLON.Scene(engine);
  82361. var specularTextures = {};
  82362. var promises = [];
  82363. // Read and collect all mipmaps data from the cube.
  82364. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82365. mipmapsCount = Math.round(mipmapsCount);
  82366. var _loop_1 = function (i) {
  82367. var faceWidth = Math.pow(2, mipmapsCount - i);
  82368. var _loop_2 = function (face) {
  82369. var data = texture.readPixels(face, i);
  82370. // Creates a temp texture with the face data.
  82371. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82372. // And rgbdEncode them.
  82373. var promise = new Promise(function (resolve, reject) {
  82374. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  82375. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82376. rgbdPostProcess.onApply = function (effect) {
  82377. effect._bindTexture("textureSampler", tempTexture);
  82378. };
  82379. // As the process needs to happen on the main canvas, keep track of the current size
  82380. var currentW = engine.getRenderWidth();
  82381. var currentH = engine.getRenderHeight();
  82382. // Set the desired size for the texture
  82383. engine.setSize(faceWidth, faceWidth);
  82384. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82385. // Reading datas from WebGL
  82386. BABYLON.Tools.ToBlob(canvas, function (blob) {
  82387. var fileReader = new FileReader();
  82388. fileReader.onload = function (event) {
  82389. var arrayBuffer = event.target.result;
  82390. specularTextures[i * 6 + face] = arrayBuffer;
  82391. resolve();
  82392. };
  82393. fileReader.readAsArrayBuffer(blob);
  82394. });
  82395. // Reapply the previous canvas size
  82396. engine.setSize(currentW, currentH);
  82397. });
  82398. });
  82399. promises.push(promise);
  82400. };
  82401. // All faces of the cube.
  82402. for (var face = 0; face < 6; face++) {
  82403. _loop_2(face);
  82404. }
  82405. };
  82406. for (var i = 0; i <= mipmapsCount; i++) {
  82407. _loop_1(i);
  82408. }
  82409. // Once all the textures haves been collected as RGBD stored in PNGs
  82410. return Promise.all(promises).then(function () {
  82411. // We can delete the hosting scene keeping track of all the creation objects
  82412. hostingScene.dispose();
  82413. // Creates the json header for the env texture
  82414. var info = {
  82415. version: 1,
  82416. width: cubeWidth,
  82417. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82418. specular: {
  82419. mipmaps: []
  82420. }
  82421. };
  82422. // Sets the specular image data information
  82423. var position = 0;
  82424. for (var i = 0; i <= mipmapsCount; i++) {
  82425. for (var face = 0; face < 6; face++) {
  82426. var byteLength = specularTextures[i * 6 + face].byteLength;
  82427. info.specular.mipmaps.push({
  82428. length: byteLength,
  82429. position: position
  82430. });
  82431. position += byteLength;
  82432. }
  82433. }
  82434. // Encode the JSON as an array buffer
  82435. var infoString = JSON.stringify(info);
  82436. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82437. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82438. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82439. infoView[i] = infoString.charCodeAt(i);
  82440. }
  82441. // Ends up with a null terminator for easier parsing
  82442. infoView[infoString.length] = 0x00;
  82443. // Computes the final required size and creates the storage
  82444. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82445. var finalBuffer = new ArrayBuffer(totalSize);
  82446. var finalBufferView = new Uint8Array(finalBuffer);
  82447. var dataView = new DataView(finalBuffer);
  82448. // Copy the magic bytes identifying the file in
  82449. var pos = 0;
  82450. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82451. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82452. }
  82453. // Add the json info
  82454. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82455. pos += infoBuffer.byteLength;
  82456. // Finally inserts the texture data
  82457. for (var i = 0; i <= mipmapsCount; i++) {
  82458. for (var face = 0; face < 6; face++) {
  82459. var dataBuffer = specularTextures[i * 6 + face];
  82460. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82461. pos += dataBuffer.byteLength;
  82462. }
  82463. }
  82464. // Voila
  82465. return finalBuffer;
  82466. });
  82467. };
  82468. /**
  82469. * Creates a JSON representation of the spherical data.
  82470. * @param texture defines the texture containing the polynomials
  82471. * @return the JSON representation of the spherical info
  82472. */
  82473. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82474. var polynmials = texture.sphericalPolynomial;
  82475. if (polynmials == null) {
  82476. return null;
  82477. }
  82478. return {
  82479. polynomials: true,
  82480. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82481. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82482. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82483. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82484. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82485. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82486. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82487. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82488. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82489. };
  82490. };
  82491. /**
  82492. * Uploads the texture info contained in the env file to te GPU.
  82493. * @param texture defines the internal texture to upload to
  82494. * @param arrayBuffer defines the buffer cotaining the data to load
  82495. * @param info defines the texture info retrieved through the GetEnvInfo method
  82496. * @returns a promise
  82497. */
  82498. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  82499. if (info.version !== 1) {
  82500. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82501. }
  82502. var specularInfo = info.specular;
  82503. if (!specularInfo) {
  82504. // Nothing else parsed so far
  82505. return Promise.resolve();
  82506. }
  82507. // Double checks the enclosed info
  82508. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82509. mipmapsCount = Math.round(mipmapsCount) + 1;
  82510. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82511. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82512. }
  82513. // Gets everything ready.
  82514. var engine = texture.getEngine();
  82515. var expandTexture = false;
  82516. var generateNonLODTextures = false;
  82517. var rgbdPostProcess = null;
  82518. var cubeRtt = null;
  82519. var lodTextures = null;
  82520. var caps = engine.getCaps();
  82521. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82522. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82523. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82524. // Add extra process if texture lod is not supported
  82525. if (!caps.textureLOD) {
  82526. expandTexture = false;
  82527. generateNonLODTextures = true;
  82528. lodTextures = {};
  82529. }
  82530. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82531. else if (engine.webGLVersion < 2) {
  82532. expandTexture = false;
  82533. }
  82534. // If half float available we can uncompress the texture
  82535. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82536. expandTexture = true;
  82537. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82538. }
  82539. // If full float available we can uncompress the texture
  82540. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82541. expandTexture = true;
  82542. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82543. }
  82544. // Expand the texture if possible
  82545. if (expandTexture) {
  82546. // Simply run through the decode PP
  82547. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82548. texture._isRGBD = false;
  82549. texture.invertY = false;
  82550. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82551. generateDepthBuffer: false,
  82552. generateMipMaps: true,
  82553. generateStencilBuffer: false,
  82554. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82555. type: texture.type,
  82556. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82557. });
  82558. }
  82559. else {
  82560. texture._isRGBD = true;
  82561. texture.invertY = true;
  82562. // In case of missing support, applies the same patch than DDS files.
  82563. if (generateNonLODTextures) {
  82564. var mipSlices = 3;
  82565. var scale = texture._lodGenerationScale;
  82566. var offset = texture._lodGenerationOffset;
  82567. for (var i = 0; i < mipSlices; i++) {
  82568. //compute LOD from even spacing in smoothness (matching shader calculation)
  82569. var smoothness = i / (mipSlices - 1);
  82570. var roughness = 1 - smoothness;
  82571. var minLODIndex = offset; // roughness = 0
  82572. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  82573. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82574. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82575. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82576. glTextureFromLod.isCube = true;
  82577. glTextureFromLod.invertY = true;
  82578. glTextureFromLod.generateMipMaps = false;
  82579. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82580. // Wrap in a base texture for easy binding.
  82581. var lodTexture = new BABYLON.BaseTexture(null);
  82582. lodTexture.isCube = true;
  82583. lodTexture._texture = glTextureFromLod;
  82584. lodTextures[mipmapIndex] = lodTexture;
  82585. switch (i) {
  82586. case 0:
  82587. texture._lodTextureLow = lodTexture;
  82588. break;
  82589. case 1:
  82590. texture._lodTextureMid = lodTexture;
  82591. break;
  82592. case 2:
  82593. texture._lodTextureHigh = lodTexture;
  82594. break;
  82595. }
  82596. }
  82597. }
  82598. }
  82599. var promises = [];
  82600. var _loop_3 = function (i) {
  82601. var _loop_4 = function (face) {
  82602. // Retrieves the face data
  82603. var imageData = specularInfo.mipmaps[i * 6 + face];
  82604. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  82605. // Constructs an image element from bytes
  82606. var blob = new Blob([bytes], { type: 'image/png' });
  82607. var url = URL.createObjectURL(blob);
  82608. var image = new Image();
  82609. image.src = url;
  82610. // Enqueue promise to upload to the texture.
  82611. var promise = new Promise(function (resolve, reject) {
  82612. ;
  82613. image.onload = function () {
  82614. if (expandTexture) {
  82615. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82616. reject(message);
  82617. }, image);
  82618. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82619. // Uncompress the data to a RTT
  82620. rgbdPostProcess.onApply = function (effect) {
  82621. effect._bindTexture("textureSampler", tempTexture_1);
  82622. effect.setFloat2("scale", 1, 1);
  82623. };
  82624. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82625. // Cleanup
  82626. engine.restoreDefaultFramebuffer();
  82627. tempTexture_1.dispose();
  82628. window.URL.revokeObjectURL(url);
  82629. resolve();
  82630. });
  82631. }
  82632. else {
  82633. engine._uploadImageToTexture(texture, face, i, image);
  82634. // Upload the face to the none lod texture support
  82635. if (generateNonLODTextures) {
  82636. var lodTexture = lodTextures[i];
  82637. if (lodTexture) {
  82638. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  82639. }
  82640. }
  82641. resolve();
  82642. }
  82643. };
  82644. image.onerror = function (error) {
  82645. reject(error);
  82646. };
  82647. });
  82648. promises.push(promise);
  82649. };
  82650. // All faces
  82651. for (var face = 0; face < 6; face++) {
  82652. _loop_4(face);
  82653. }
  82654. };
  82655. // All mipmaps
  82656. for (var i = 0; i < mipmapsCount; i++) {
  82657. _loop_3(i);
  82658. }
  82659. // Once all done, finishes the cleanup and return
  82660. return Promise.all(promises).then(function () {
  82661. // Relase temp RTT.
  82662. if (cubeRtt) {
  82663. engine._releaseFramebufferObjects(cubeRtt);
  82664. cubeRtt._swapAndDie(texture);
  82665. }
  82666. // Relase temp Post Process.
  82667. if (rgbdPostProcess) {
  82668. rgbdPostProcess.dispose();
  82669. }
  82670. // Flag internal texture as ready in case they are in use.
  82671. if (generateNonLODTextures) {
  82672. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82673. texture._lodTextureHigh._texture.isReady = true;
  82674. }
  82675. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82676. texture._lodTextureMid._texture.isReady = true;
  82677. }
  82678. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82679. texture._lodTextureLow._texture.isReady = true;
  82680. }
  82681. }
  82682. });
  82683. };
  82684. /**
  82685. * Uploads spherical polynomials information to the texture.
  82686. * @param texture defines the texture we are trying to upload the information to
  82687. * @param arrayBuffer defines the array buffer holding the data
  82688. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82689. */
  82690. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  82691. if (info.version !== 1) {
  82692. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82693. }
  82694. var irradianceInfo = info.irradiance;
  82695. if (!irradianceInfo) {
  82696. return;
  82697. }
  82698. //harmonics now represent radiance
  82699. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  82700. if (irradianceInfo.polynomials) {
  82701. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  82702. }
  82703. else {
  82704. // convert From SH to SP.
  82705. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  82706. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  82707. }
  82708. };
  82709. /**
  82710. * Upload spherical polynomial coefficients to the texture
  82711. * @param polynmials Spherical polynmial coefficients (9)
  82712. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82713. */
  82714. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  82715. outPolynomialCoefficents.x.x = polynmials.x[0];
  82716. outPolynomialCoefficents.x.y = polynmials.x[1];
  82717. outPolynomialCoefficents.x.z = polynmials.x[2];
  82718. outPolynomialCoefficents.y.x = polynmials.y[0];
  82719. outPolynomialCoefficents.y.y = polynmials.y[1];
  82720. outPolynomialCoefficents.y.z = polynmials.y[2];
  82721. outPolynomialCoefficents.z.x = polynmials.z[0];
  82722. outPolynomialCoefficents.z.y = polynmials.z[1];
  82723. outPolynomialCoefficents.z.z = polynmials.z[2];
  82724. //xx
  82725. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  82726. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  82727. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  82728. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  82729. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  82730. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  82731. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  82732. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  82733. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  82734. //yz
  82735. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  82736. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  82737. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  82738. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  82739. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  82740. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  82741. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  82742. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  82743. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  82744. };
  82745. /**
  82746. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82747. * L = (1/pi) * E * rho
  82748. *
  82749. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82750. * @param harmonics Spherical harmonic coefficients (9)
  82751. */
  82752. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  82753. var scaleFactor = 1 / Math.PI;
  82754. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82755. // (The pixel shader must apply albedo after texture fetches, etc).
  82756. harmonics.l00[0] *= scaleFactor;
  82757. harmonics.l00[1] *= scaleFactor;
  82758. harmonics.l00[2] *= scaleFactor;
  82759. harmonics.l1_1[0] *= scaleFactor;
  82760. harmonics.l1_1[1] *= scaleFactor;
  82761. harmonics.l1_1[2] *= scaleFactor;
  82762. harmonics.l10[0] *= scaleFactor;
  82763. harmonics.l10[1] *= scaleFactor;
  82764. harmonics.l10[2] *= scaleFactor;
  82765. harmonics.l11[0] *= scaleFactor;
  82766. harmonics.l11[1] *= scaleFactor;
  82767. harmonics.l11[2] *= scaleFactor;
  82768. harmonics.l2_2[0] *= scaleFactor;
  82769. harmonics.l2_2[1] *= scaleFactor;
  82770. harmonics.l2_2[2] *= scaleFactor;
  82771. harmonics.l2_1[0] *= scaleFactor;
  82772. harmonics.l2_1[1] *= scaleFactor;
  82773. harmonics.l2_1[2] *= scaleFactor;
  82774. harmonics.l20[0] *= scaleFactor;
  82775. harmonics.l20[1] *= scaleFactor;
  82776. harmonics.l20[2] *= scaleFactor;
  82777. harmonics.l21[0] *= scaleFactor;
  82778. harmonics.l21[1] *= scaleFactor;
  82779. harmonics.l21[2] *= scaleFactor;
  82780. harmonics.l22[0] *= scaleFactor;
  82781. harmonics.l22[1] *= scaleFactor;
  82782. harmonics.l22[2] *= scaleFactor;
  82783. };
  82784. /**
  82785. * Convert spherical harmonics to spherical polynomial coefficients
  82786. * @param harmonics Spherical harmonic coefficients (9)
  82787. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82788. */
  82789. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  82790. var rPi = 1 / Math.PI;
  82791. //x
  82792. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  82793. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  82794. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  82795. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  82796. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  82797. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  82798. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  82799. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  82800. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  82801. //xx
  82802. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82803. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82804. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82805. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82806. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82807. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82808. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82809. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82810. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82811. //yz
  82812. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82813. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82814. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82815. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82816. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82817. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82818. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82819. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82820. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82821. };
  82822. /**
  82823. * Magic number identifying the env file.
  82824. */
  82825. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82826. return EnvironmentTextureTools;
  82827. }());
  82828. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82829. })(BABYLON || (BABYLON = {}));
  82830. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82831. var BABYLON;
  82832. (function (BABYLON) {
  82833. /**
  82834. * This represents a texture coming from an HDR input.
  82835. *
  82836. * The only supported format is currently panorama picture stored in RGBE format.
  82837. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82838. */
  82839. var HDRCubeTexture = /** @class */ (function (_super) {
  82840. __extends(HDRCubeTexture, _super);
  82841. /**
  82842. * Instantiates an HDRTexture from the following parameters.
  82843. *
  82844. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82845. * @param scene The scene the texture will be used in
  82846. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82847. * @param noMipmap Forces to not generate the mipmap if true
  82848. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82849. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  82850. * @param reserved Reserved flag for internal use.
  82851. */
  82852. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82853. if (noMipmap === void 0) { noMipmap = false; }
  82854. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82855. if (gammaSpace === void 0) { gammaSpace = false; }
  82856. if (reserved === void 0) { reserved = false; }
  82857. if (onLoad === void 0) { onLoad = null; }
  82858. if (onError === void 0) { onError = null; }
  82859. var _this = _super.call(this, scene) || this;
  82860. _this._generateHarmonics = true;
  82861. _this._onLoad = null;
  82862. _this._onError = null;
  82863. /**
  82864. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82865. */
  82866. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82867. _this._isBlocking = true;
  82868. _this._rotationY = 0;
  82869. /**
  82870. * Gets or sets the center of the bounding box associated with the cube texture
  82871. * It must define where the camera used to render the texture was set
  82872. */
  82873. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82874. if (!url) {
  82875. return _this;
  82876. }
  82877. _this.name = url;
  82878. _this.url = url;
  82879. _this.hasAlpha = false;
  82880. _this.isCube = true;
  82881. _this._textureMatrix = BABYLON.Matrix.Identity();
  82882. _this._onLoad = onLoad;
  82883. _this._onError = onError;
  82884. _this.gammaSpace = gammaSpace;
  82885. _this._noMipmap = noMipmap;
  82886. _this._size = size;
  82887. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82888. if (!_this._texture) {
  82889. if (!scene.useDelayedTextureLoading) {
  82890. _this.loadTexture();
  82891. }
  82892. else {
  82893. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82894. }
  82895. }
  82896. return _this;
  82897. }
  82898. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82899. /**
  82900. * Gets wether or not the texture is blocking during loading.
  82901. */
  82902. get: function () {
  82903. return this._isBlocking;
  82904. },
  82905. /**
  82906. * Sets wether or not the texture is blocking during loading.
  82907. */
  82908. set: function (value) {
  82909. this._isBlocking = value;
  82910. },
  82911. enumerable: true,
  82912. configurable: true
  82913. });
  82914. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82915. /**
  82916. * Gets texture matrix rotation angle around Y axis radians.
  82917. */
  82918. get: function () {
  82919. return this._rotationY;
  82920. },
  82921. /**
  82922. * Sets texture matrix rotation angle around Y axis in radians.
  82923. */
  82924. set: function (value) {
  82925. this._rotationY = value;
  82926. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82927. },
  82928. enumerable: true,
  82929. configurable: true
  82930. });
  82931. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82932. get: function () {
  82933. return this._boundingBoxSize;
  82934. },
  82935. /**
  82936. * Gets or sets the size of the bounding box associated with the cube texture
  82937. * When defined, the cubemap will switch to local mode
  82938. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82939. * @example https://www.babylonjs-playground.com/#RNASML
  82940. */
  82941. set: function (value) {
  82942. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82943. return;
  82944. }
  82945. this._boundingBoxSize = value;
  82946. var scene = this.getScene();
  82947. if (scene) {
  82948. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  82949. }
  82950. },
  82951. enumerable: true,
  82952. configurable: true
  82953. });
  82954. /**
  82955. * Occurs when the file is raw .hdr file.
  82956. */
  82957. HDRCubeTexture.prototype.loadTexture = function () {
  82958. var _this = this;
  82959. var callback = function (buffer) {
  82960. _this.lodGenerationOffset = 0.0;
  82961. _this.lodGenerationScale = 0.8;
  82962. var scene = _this.getScene();
  82963. if (!scene) {
  82964. return null;
  82965. }
  82966. // Extract the raw linear data.
  82967. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  82968. // Generate harmonics if needed.
  82969. if (_this._generateHarmonics) {
  82970. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  82971. _this.sphericalPolynomial = sphericalPolynomial;
  82972. }
  82973. var results = [];
  82974. var byteArray = null;
  82975. // Push each faces.
  82976. for (var j = 0; j < 6; j++) {
  82977. // Create uintarray fallback.
  82978. if (!scene.getEngine().getCaps().textureFloat) {
  82979. // 3 channels of 1 bytes per pixel in bytes.
  82980. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  82981. byteArray = new Uint8Array(byteBuffer);
  82982. }
  82983. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  82984. // If special cases.
  82985. if (_this.gammaSpace || byteArray) {
  82986. for (var i = 0; i < _this._size * _this._size; i++) {
  82987. // Put in gamma space if requested.
  82988. if (_this.gammaSpace) {
  82989. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  82990. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  82991. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  82992. }
  82993. // Convert to int texture for fallback.
  82994. if (byteArray) {
  82995. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  82996. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  82997. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  82998. // May use luminance instead if the result is not accurate.
  82999. var max = Math.max(Math.max(r, g), b);
  83000. if (max > 255) {
  83001. var scale = 255 / max;
  83002. r *= scale;
  83003. g *= scale;
  83004. b *= scale;
  83005. }
  83006. byteArray[(i * 3) + 0] = r;
  83007. byteArray[(i * 3) + 1] = g;
  83008. byteArray[(i * 3) + 2] = b;
  83009. }
  83010. }
  83011. }
  83012. if (byteArray) {
  83013. results.push(byteArray);
  83014. }
  83015. else {
  83016. results.push(dataFace);
  83017. }
  83018. }
  83019. return results;
  83020. };
  83021. var scene = this.getScene();
  83022. if (scene) {
  83023. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  83024. }
  83025. };
  83026. HDRCubeTexture.prototype.clone = function () {
  83027. var scene = this.getScene();
  83028. if (!scene) {
  83029. return this;
  83030. }
  83031. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83032. // Base texture
  83033. newTexture.level = this.level;
  83034. newTexture.wrapU = this.wrapU;
  83035. newTexture.wrapV = this.wrapV;
  83036. newTexture.coordinatesIndex = this.coordinatesIndex;
  83037. newTexture.coordinatesMode = this.coordinatesMode;
  83038. return newTexture;
  83039. };
  83040. // Methods
  83041. HDRCubeTexture.prototype.delayLoad = function () {
  83042. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83043. return;
  83044. }
  83045. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83046. this._texture = this._getFromCache(this.url, this._noMipmap);
  83047. if (!this._texture) {
  83048. this.loadTexture();
  83049. }
  83050. };
  83051. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83052. return this._textureMatrix;
  83053. };
  83054. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83055. this._textureMatrix = value;
  83056. };
  83057. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83058. var texture = null;
  83059. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83060. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83061. texture.name = parsedTexture.name;
  83062. texture.hasAlpha = parsedTexture.hasAlpha;
  83063. texture.level = parsedTexture.level;
  83064. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83065. texture.isBlocking = parsedTexture.isBlocking;
  83066. }
  83067. if (texture) {
  83068. if (parsedTexture.boundingBoxPosition) {
  83069. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83070. }
  83071. if (parsedTexture.boundingBoxSize) {
  83072. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83073. }
  83074. if (parsedTexture.rotationY) {
  83075. texture.rotationY = parsedTexture.rotationY;
  83076. }
  83077. }
  83078. return texture;
  83079. };
  83080. HDRCubeTexture.prototype.serialize = function () {
  83081. if (!this.name) {
  83082. return null;
  83083. }
  83084. var serializationObject = {};
  83085. serializationObject.name = this.name;
  83086. serializationObject.hasAlpha = this.hasAlpha;
  83087. serializationObject.isCube = true;
  83088. serializationObject.level = this.level;
  83089. serializationObject.size = this._size;
  83090. serializationObject.coordinatesMode = this.coordinatesMode;
  83091. serializationObject.useInGammaSpace = this.gammaSpace;
  83092. serializationObject.generateHarmonics = this._generateHarmonics;
  83093. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83094. serializationObject.noMipmap = this._noMipmap;
  83095. serializationObject.isBlocking = this._isBlocking;
  83096. serializationObject.rotationY = this._rotationY;
  83097. return serializationObject;
  83098. };
  83099. HDRCubeTexture._facesMapping = [
  83100. "right",
  83101. "left",
  83102. "up",
  83103. "down",
  83104. "front",
  83105. "back"
  83106. ];
  83107. return HDRCubeTexture;
  83108. }(BABYLON.BaseTexture));
  83109. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83110. })(BABYLON || (BABYLON = {}));
  83111. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83112. var BABYLON;
  83113. (function (BABYLON) {
  83114. var IndexedVector2 = /** @class */ (function (_super) {
  83115. __extends(IndexedVector2, _super);
  83116. function IndexedVector2(original, index) {
  83117. var _this = _super.call(this, original.x, original.y) || this;
  83118. _this.index = index;
  83119. return _this;
  83120. }
  83121. return IndexedVector2;
  83122. }(BABYLON.Vector2));
  83123. var PolygonPoints = /** @class */ (function () {
  83124. function PolygonPoints() {
  83125. this.elements = new Array();
  83126. }
  83127. PolygonPoints.prototype.add = function (originalPoints) {
  83128. var _this = this;
  83129. var result = new Array();
  83130. originalPoints.forEach(function (point) {
  83131. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83132. var newPoint = new IndexedVector2(point, _this.elements.length);
  83133. result.push(newPoint);
  83134. _this.elements.push(newPoint);
  83135. }
  83136. });
  83137. return result;
  83138. };
  83139. PolygonPoints.prototype.computeBounds = function () {
  83140. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83141. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83142. this.elements.forEach(function (point) {
  83143. // x
  83144. if (point.x < lmin.x) {
  83145. lmin.x = point.x;
  83146. }
  83147. else if (point.x > lmax.x) {
  83148. lmax.x = point.x;
  83149. }
  83150. // y
  83151. if (point.y < lmin.y) {
  83152. lmin.y = point.y;
  83153. }
  83154. else if (point.y > lmax.y) {
  83155. lmax.y = point.y;
  83156. }
  83157. });
  83158. return {
  83159. min: lmin,
  83160. max: lmax,
  83161. width: lmax.x - lmin.x,
  83162. height: lmax.y - lmin.y
  83163. };
  83164. };
  83165. return PolygonPoints;
  83166. }());
  83167. var Polygon = /** @class */ (function () {
  83168. function Polygon() {
  83169. }
  83170. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83171. return [
  83172. new BABYLON.Vector2(xmin, ymin),
  83173. new BABYLON.Vector2(xmax, ymin),
  83174. new BABYLON.Vector2(xmax, ymax),
  83175. new BABYLON.Vector2(xmin, ymax)
  83176. ];
  83177. };
  83178. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83179. if (cx === void 0) { cx = 0; }
  83180. if (cy === void 0) { cy = 0; }
  83181. if (numberOfSides === void 0) { numberOfSides = 32; }
  83182. var result = new Array();
  83183. var angle = 0;
  83184. var increment = (Math.PI * 2) / numberOfSides;
  83185. for (var i = 0; i < numberOfSides; i++) {
  83186. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83187. angle -= increment;
  83188. }
  83189. return result;
  83190. };
  83191. Polygon.Parse = function (input) {
  83192. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83193. var i, result = [];
  83194. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83195. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83196. }
  83197. return result;
  83198. };
  83199. Polygon.StartingAt = function (x, y) {
  83200. return BABYLON.Path2.StartingAt(x, y);
  83201. };
  83202. return Polygon;
  83203. }());
  83204. BABYLON.Polygon = Polygon;
  83205. var PolygonMeshBuilder = /** @class */ (function () {
  83206. function PolygonMeshBuilder(name, contours, scene) {
  83207. this._points = new PolygonPoints();
  83208. this._outlinepoints = new PolygonPoints();
  83209. this._holes = new Array();
  83210. this._epoints = new Array();
  83211. this._eholes = new Array();
  83212. this._name = name;
  83213. this._scene = scene;
  83214. var points;
  83215. if (contours instanceof BABYLON.Path2) {
  83216. points = contours.getPoints();
  83217. }
  83218. else {
  83219. points = contours;
  83220. }
  83221. this._addToepoint(points);
  83222. this._points.add(points);
  83223. this._outlinepoints.add(points);
  83224. if (typeof earcut === 'undefined') {
  83225. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83226. }
  83227. }
  83228. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83229. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83230. var p = points_1[_i];
  83231. this._epoints.push(p.x, p.y);
  83232. }
  83233. };
  83234. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83235. this._points.add(hole);
  83236. var holepoints = new PolygonPoints();
  83237. holepoints.add(hole);
  83238. this._holes.push(holepoints);
  83239. this._eholes.push(this._epoints.length / 2);
  83240. this._addToepoint(hole);
  83241. return this;
  83242. };
  83243. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83244. var _this = this;
  83245. if (updatable === void 0) { updatable = false; }
  83246. if (depth === void 0) { depth = 0; }
  83247. var result = new BABYLON.Mesh(this._name, this._scene);
  83248. var normals = new Array();
  83249. var positions = new Array();
  83250. var uvs = new Array();
  83251. var bounds = this._points.computeBounds();
  83252. this._points.elements.forEach(function (p) {
  83253. normals.push(0, 1.0, 0);
  83254. positions.push(p.x, 0, p.y);
  83255. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83256. });
  83257. var indices = new Array();
  83258. var res = earcut(this._epoints, this._eholes, 2);
  83259. for (var i = 0; i < res.length; i++) {
  83260. indices.push(res[i]);
  83261. }
  83262. if (depth > 0) {
  83263. var positionscount = (positions.length / 3); //get the current pointcount
  83264. this._points.elements.forEach(function (p) {
  83265. normals.push(0, -1.0, 0);
  83266. positions.push(p.x, -depth, p.y);
  83267. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83268. });
  83269. var totalCount = indices.length;
  83270. for (var i = 0; i < totalCount; i += 3) {
  83271. var i0 = indices[i + 0];
  83272. var i1 = indices[i + 1];
  83273. var i2 = indices[i + 2];
  83274. indices.push(i2 + positionscount);
  83275. indices.push(i1 + positionscount);
  83276. indices.push(i0 + positionscount);
  83277. }
  83278. //Add the sides
  83279. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83280. this._holes.forEach(function (hole) {
  83281. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83282. });
  83283. }
  83284. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83285. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83286. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83287. result.setIndices(indices);
  83288. return result;
  83289. };
  83290. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83291. var StartIndex = positions.length / 3;
  83292. var ulength = 0;
  83293. for (var i = 0; i < points.elements.length; i++) {
  83294. var p = points.elements[i];
  83295. var p1;
  83296. if ((i + 1) > points.elements.length - 1) {
  83297. p1 = points.elements[0];
  83298. }
  83299. else {
  83300. p1 = points.elements[i + 1];
  83301. }
  83302. positions.push(p.x, 0, p.y);
  83303. positions.push(p.x, -depth, p.y);
  83304. positions.push(p1.x, 0, p1.y);
  83305. positions.push(p1.x, -depth, p1.y);
  83306. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83307. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83308. var v3 = v2.subtract(v1);
  83309. var v4 = new BABYLON.Vector3(0, 1, 0);
  83310. var vn = BABYLON.Vector3.Cross(v3, v4);
  83311. vn = vn.normalize();
  83312. uvs.push(ulength / bounds.width, 0);
  83313. uvs.push(ulength / bounds.width, 1);
  83314. ulength += v3.length();
  83315. uvs.push((ulength / bounds.width), 0);
  83316. uvs.push((ulength / bounds.width), 1);
  83317. if (!flip) {
  83318. normals.push(-vn.x, -vn.y, -vn.z);
  83319. normals.push(-vn.x, -vn.y, -vn.z);
  83320. normals.push(-vn.x, -vn.y, -vn.z);
  83321. normals.push(-vn.x, -vn.y, -vn.z);
  83322. indices.push(StartIndex);
  83323. indices.push(StartIndex + 1);
  83324. indices.push(StartIndex + 2);
  83325. indices.push(StartIndex + 1);
  83326. indices.push(StartIndex + 3);
  83327. indices.push(StartIndex + 2);
  83328. }
  83329. else {
  83330. normals.push(vn.x, vn.y, vn.z);
  83331. normals.push(vn.x, vn.y, vn.z);
  83332. normals.push(vn.x, vn.y, vn.z);
  83333. normals.push(vn.x, vn.y, vn.z);
  83334. indices.push(StartIndex);
  83335. indices.push(StartIndex + 2);
  83336. indices.push(StartIndex + 1);
  83337. indices.push(StartIndex + 1);
  83338. indices.push(StartIndex + 2);
  83339. indices.push(StartIndex + 3);
  83340. }
  83341. StartIndex += 4;
  83342. }
  83343. ;
  83344. };
  83345. return PolygonMeshBuilder;
  83346. }());
  83347. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83348. })(BABYLON || (BABYLON = {}));
  83349. //# sourceMappingURL=babylon.polygonMesh.js.map
  83350. var BABYLON;
  83351. (function (BABYLON) {
  83352. // Unique ID when we import meshes from Babylon to CSG
  83353. var currentCSGMeshId = 0;
  83354. // # class Vertex
  83355. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83356. // one to provide additional features like texture coordinates and vertex
  83357. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83358. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83359. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83360. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83361. // is not used anywhere else.
  83362. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83363. var Vertex = /** @class */ (function () {
  83364. function Vertex(pos, normal, uv) {
  83365. this.pos = pos;
  83366. this.normal = normal;
  83367. this.uv = uv;
  83368. }
  83369. Vertex.prototype.clone = function () {
  83370. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83371. };
  83372. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83373. // orientation of a polygon is flipped.
  83374. Vertex.prototype.flip = function () {
  83375. this.normal = this.normal.scale(-1);
  83376. };
  83377. // Create a new vertex between this vertex and `other` by linearly
  83378. // interpolating all properties using a parameter of `t`. Subclasses should
  83379. // override this to interpolate additional properties.
  83380. Vertex.prototype.interpolate = function (other, t) {
  83381. 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));
  83382. };
  83383. return Vertex;
  83384. }());
  83385. // # class Plane
  83386. // Represents a plane in 3D space.
  83387. var Plane = /** @class */ (function () {
  83388. function Plane(normal, w) {
  83389. this.normal = normal;
  83390. this.w = w;
  83391. }
  83392. Plane.FromPoints = function (a, b, c) {
  83393. var v0 = c.subtract(a);
  83394. var v1 = b.subtract(a);
  83395. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83396. return null;
  83397. }
  83398. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83399. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83400. };
  83401. Plane.prototype.clone = function () {
  83402. return new Plane(this.normal.clone(), this.w);
  83403. };
  83404. Plane.prototype.flip = function () {
  83405. this.normal.scaleInPlace(-1);
  83406. this.w = -this.w;
  83407. };
  83408. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83409. // fragments in the appropriate lists. Coplanar polygons go into either
  83410. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83411. // respect to this plane. Polygons in front or in back of this plane go into
  83412. // either `front` or `back`.
  83413. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83414. var COPLANAR = 0;
  83415. var FRONT = 1;
  83416. var BACK = 2;
  83417. var SPANNING = 3;
  83418. // Classify each point as well as the entire polygon into one of the above
  83419. // four classes.
  83420. var polygonType = 0;
  83421. var types = [];
  83422. var i;
  83423. var t;
  83424. for (i = 0; i < polygon.vertices.length; i++) {
  83425. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83426. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83427. polygonType |= type;
  83428. types.push(type);
  83429. }
  83430. // Put the polygon in the correct list, splitting it when necessary.
  83431. switch (polygonType) {
  83432. case COPLANAR:
  83433. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83434. break;
  83435. case FRONT:
  83436. front.push(polygon);
  83437. break;
  83438. case BACK:
  83439. back.push(polygon);
  83440. break;
  83441. case SPANNING:
  83442. var f = [], b = [];
  83443. for (i = 0; i < polygon.vertices.length; i++) {
  83444. var j = (i + 1) % polygon.vertices.length;
  83445. var ti = types[i], tj = types[j];
  83446. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83447. if (ti !== BACK)
  83448. f.push(vi);
  83449. if (ti !== FRONT)
  83450. b.push(ti !== BACK ? vi.clone() : vi);
  83451. if ((ti | tj) === SPANNING) {
  83452. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83453. var v = vi.interpolate(vj, t);
  83454. f.push(v);
  83455. b.push(v.clone());
  83456. }
  83457. }
  83458. var poly;
  83459. if (f.length >= 3) {
  83460. poly = new Polygon(f, polygon.shared);
  83461. if (poly.plane)
  83462. front.push(poly);
  83463. }
  83464. if (b.length >= 3) {
  83465. poly = new Polygon(b, polygon.shared);
  83466. if (poly.plane)
  83467. back.push(poly);
  83468. }
  83469. break;
  83470. }
  83471. };
  83472. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83473. // point is on the plane.
  83474. Plane.EPSILON = 1e-5;
  83475. return Plane;
  83476. }());
  83477. // # class Polygon
  83478. // Represents a convex polygon. The vertices used to initialize a polygon must
  83479. // be coplanar and form a convex loop.
  83480. //
  83481. // Each convex polygon has a `shared` property, which is shared between all
  83482. // polygons that are clones of each other or were split from the same polygon.
  83483. // This can be used to define per-polygon properties (such as surface color).
  83484. var Polygon = /** @class */ (function () {
  83485. function Polygon(vertices, shared) {
  83486. this.vertices = vertices;
  83487. this.shared = shared;
  83488. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83489. }
  83490. Polygon.prototype.clone = function () {
  83491. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83492. return new Polygon(vertices, this.shared);
  83493. };
  83494. Polygon.prototype.flip = function () {
  83495. this.vertices.reverse().map(function (v) { v.flip(); });
  83496. this.plane.flip();
  83497. };
  83498. return Polygon;
  83499. }());
  83500. // # class Node
  83501. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83502. // by picking a polygon to split along. That polygon (and all other coplanar
  83503. // polygons) are added directly to that node and the other polygons are added to
  83504. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83505. // no distinction between internal and leaf nodes.
  83506. var Node = /** @class */ (function () {
  83507. function Node(polygons) {
  83508. this.plane = null;
  83509. this.front = null;
  83510. this.back = null;
  83511. this.polygons = new Array();
  83512. if (polygons) {
  83513. this.build(polygons);
  83514. }
  83515. }
  83516. Node.prototype.clone = function () {
  83517. var node = new Node();
  83518. node.plane = this.plane && this.plane.clone();
  83519. node.front = this.front && this.front.clone();
  83520. node.back = this.back && this.back.clone();
  83521. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83522. return node;
  83523. };
  83524. // Convert solid space to empty space and empty space to solid space.
  83525. Node.prototype.invert = function () {
  83526. for (var i = 0; i < this.polygons.length; i++) {
  83527. this.polygons[i].flip();
  83528. }
  83529. if (this.plane) {
  83530. this.plane.flip();
  83531. }
  83532. if (this.front) {
  83533. this.front.invert();
  83534. }
  83535. if (this.back) {
  83536. this.back.invert();
  83537. }
  83538. var temp = this.front;
  83539. this.front = this.back;
  83540. this.back = temp;
  83541. };
  83542. // Recursively remove all polygons in `polygons` that are inside this BSP
  83543. // tree.
  83544. Node.prototype.clipPolygons = function (polygons) {
  83545. if (!this.plane)
  83546. return polygons.slice();
  83547. var front = new Array(), back = new Array();
  83548. for (var i = 0; i < polygons.length; i++) {
  83549. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83550. }
  83551. if (this.front) {
  83552. front = this.front.clipPolygons(front);
  83553. }
  83554. if (this.back) {
  83555. back = this.back.clipPolygons(back);
  83556. }
  83557. else {
  83558. back = [];
  83559. }
  83560. return front.concat(back);
  83561. };
  83562. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83563. // `bsp`.
  83564. Node.prototype.clipTo = function (bsp) {
  83565. this.polygons = bsp.clipPolygons(this.polygons);
  83566. if (this.front)
  83567. this.front.clipTo(bsp);
  83568. if (this.back)
  83569. this.back.clipTo(bsp);
  83570. };
  83571. // Return a list of all polygons in this BSP tree.
  83572. Node.prototype.allPolygons = function () {
  83573. var polygons = this.polygons.slice();
  83574. if (this.front)
  83575. polygons = polygons.concat(this.front.allPolygons());
  83576. if (this.back)
  83577. polygons = polygons.concat(this.back.allPolygons());
  83578. return polygons;
  83579. };
  83580. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83581. // new polygons are filtered down to the bottom of the tree and become new
  83582. // nodes there. Each set of polygons is partitioned using the first polygon
  83583. // (no heuristic is used to pick a good split).
  83584. Node.prototype.build = function (polygons) {
  83585. if (!polygons.length)
  83586. return;
  83587. if (!this.plane)
  83588. this.plane = polygons[0].plane.clone();
  83589. var front = new Array(), back = new Array();
  83590. for (var i = 0; i < polygons.length; i++) {
  83591. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83592. }
  83593. if (front.length) {
  83594. if (!this.front)
  83595. this.front = new Node();
  83596. this.front.build(front);
  83597. }
  83598. if (back.length) {
  83599. if (!this.back)
  83600. this.back = new Node();
  83601. this.back.build(back);
  83602. }
  83603. };
  83604. return Node;
  83605. }());
  83606. var CSG = /** @class */ (function () {
  83607. function CSG() {
  83608. this.polygons = new Array();
  83609. }
  83610. // Convert BABYLON.Mesh to BABYLON.CSG
  83611. CSG.FromMesh = function (mesh) {
  83612. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83613. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83614. if (mesh instanceof BABYLON.Mesh) {
  83615. mesh.computeWorldMatrix(true);
  83616. matrix = mesh.getWorldMatrix();
  83617. meshPosition = mesh.position.clone();
  83618. meshRotation = mesh.rotation.clone();
  83619. if (mesh.rotationQuaternion) {
  83620. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83621. }
  83622. meshScaling = mesh.scaling.clone();
  83623. }
  83624. else {
  83625. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83626. }
  83627. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83628. var subMeshes = mesh.subMeshes;
  83629. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83630. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83631. vertices = [];
  83632. for (var j = 0; j < 3; j++) {
  83633. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83634. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83635. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83636. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83637. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83638. vertex = new Vertex(position, normal, uv);
  83639. vertices.push(vertex);
  83640. }
  83641. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83642. // To handle the case of degenerated triangle
  83643. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83644. if (polygon.plane)
  83645. polygons.push(polygon);
  83646. }
  83647. }
  83648. var csg = CSG.FromPolygons(polygons);
  83649. csg.matrix = matrix;
  83650. csg.position = meshPosition;
  83651. csg.rotation = meshRotation;
  83652. csg.scaling = meshScaling;
  83653. csg.rotationQuaternion = meshRotationQuaternion;
  83654. currentCSGMeshId++;
  83655. return csg;
  83656. };
  83657. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83658. CSG.FromPolygons = function (polygons) {
  83659. var csg = new CSG();
  83660. csg.polygons = polygons;
  83661. return csg;
  83662. };
  83663. CSG.prototype.clone = function () {
  83664. var csg = new CSG();
  83665. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83666. csg.copyTransformAttributes(this);
  83667. return csg;
  83668. };
  83669. CSG.prototype.union = function (csg) {
  83670. var a = new Node(this.clone().polygons);
  83671. var b = new Node(csg.clone().polygons);
  83672. a.clipTo(b);
  83673. b.clipTo(a);
  83674. b.invert();
  83675. b.clipTo(a);
  83676. b.invert();
  83677. a.build(b.allPolygons());
  83678. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83679. };
  83680. CSG.prototype.unionInPlace = function (csg) {
  83681. var a = new Node(this.polygons);
  83682. var b = new Node(csg.polygons);
  83683. a.clipTo(b);
  83684. b.clipTo(a);
  83685. b.invert();
  83686. b.clipTo(a);
  83687. b.invert();
  83688. a.build(b.allPolygons());
  83689. this.polygons = a.allPolygons();
  83690. };
  83691. CSG.prototype.subtract = function (csg) {
  83692. var a = new Node(this.clone().polygons);
  83693. var b = new Node(csg.clone().polygons);
  83694. a.invert();
  83695. a.clipTo(b);
  83696. b.clipTo(a);
  83697. b.invert();
  83698. b.clipTo(a);
  83699. b.invert();
  83700. a.build(b.allPolygons());
  83701. a.invert();
  83702. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83703. };
  83704. CSG.prototype.subtractInPlace = function (csg) {
  83705. var a = new Node(this.polygons);
  83706. var b = new Node(csg.polygons);
  83707. a.invert();
  83708. a.clipTo(b);
  83709. b.clipTo(a);
  83710. b.invert();
  83711. b.clipTo(a);
  83712. b.invert();
  83713. a.build(b.allPolygons());
  83714. a.invert();
  83715. this.polygons = a.allPolygons();
  83716. };
  83717. CSG.prototype.intersect = function (csg) {
  83718. var a = new Node(this.clone().polygons);
  83719. var b = new Node(csg.clone().polygons);
  83720. a.invert();
  83721. b.clipTo(a);
  83722. b.invert();
  83723. a.clipTo(b);
  83724. b.clipTo(a);
  83725. a.build(b.allPolygons());
  83726. a.invert();
  83727. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83728. };
  83729. CSG.prototype.intersectInPlace = function (csg) {
  83730. var a = new Node(this.polygons);
  83731. var b = new Node(csg.polygons);
  83732. a.invert();
  83733. b.clipTo(a);
  83734. b.invert();
  83735. a.clipTo(b);
  83736. b.clipTo(a);
  83737. a.build(b.allPolygons());
  83738. a.invert();
  83739. this.polygons = a.allPolygons();
  83740. };
  83741. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83742. // not modified.
  83743. CSG.prototype.inverse = function () {
  83744. var csg = this.clone();
  83745. csg.inverseInPlace();
  83746. return csg;
  83747. };
  83748. CSG.prototype.inverseInPlace = function () {
  83749. this.polygons.map(function (p) { p.flip(); });
  83750. };
  83751. // This is used to keep meshes transformations so they can be restored
  83752. // when we build back a Babylon Mesh
  83753. // NB : All CSG operations are performed in world coordinates
  83754. CSG.prototype.copyTransformAttributes = function (csg) {
  83755. this.matrix = csg.matrix;
  83756. this.position = csg.position;
  83757. this.rotation = csg.rotation;
  83758. this.scaling = csg.scaling;
  83759. this.rotationQuaternion = csg.rotationQuaternion;
  83760. return this;
  83761. };
  83762. // Build Raw mesh from CSG
  83763. // Coordinates here are in world space
  83764. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83765. var matrix = this.matrix.clone();
  83766. matrix.invert();
  83767. 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;
  83768. if (keepSubMeshes) {
  83769. // Sort Polygons, since subMeshes are indices range
  83770. polygons.sort(function (a, b) {
  83771. if (a.shared.meshId === b.shared.meshId) {
  83772. return a.shared.subMeshId - b.shared.subMeshId;
  83773. }
  83774. else {
  83775. return a.shared.meshId - b.shared.meshId;
  83776. }
  83777. });
  83778. }
  83779. for (var i = 0, il = polygons.length; i < il; i++) {
  83780. polygon = polygons[i];
  83781. // Building SubMeshes
  83782. if (!subMesh_dict[polygon.shared.meshId]) {
  83783. subMesh_dict[polygon.shared.meshId] = {};
  83784. }
  83785. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83786. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83787. indexStart: +Infinity,
  83788. indexEnd: -Infinity,
  83789. materialIndex: polygon.shared.materialIndex
  83790. };
  83791. }
  83792. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83793. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83794. polygonIndices[0] = 0;
  83795. polygonIndices[1] = j - 1;
  83796. polygonIndices[2] = j;
  83797. for (var k = 0; k < 3; k++) {
  83798. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83799. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83800. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83801. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83802. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83803. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83804. // Check if 2 points can be merged
  83805. if (!(typeof vertex_idx !== 'undefined' &&
  83806. normals[vertex_idx * 3] === localNormal.x &&
  83807. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83808. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83809. uvs[vertex_idx * 2] === uv.x &&
  83810. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83811. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83812. uvs.push(uv.x, uv.y);
  83813. normals.push(normal.x, normal.y, normal.z);
  83814. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83815. }
  83816. indices.push(vertex_idx);
  83817. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83818. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83819. currentIndex++;
  83820. }
  83821. }
  83822. }
  83823. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83824. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83825. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83826. mesh.setIndices(indices, null);
  83827. if (keepSubMeshes) {
  83828. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83829. var materialIndexOffset = 0, materialMaxIndex;
  83830. mesh.subMeshes = new Array();
  83831. for (var m in subMesh_dict) {
  83832. materialMaxIndex = -1;
  83833. for (var sm in subMesh_dict[m]) {
  83834. subMesh_obj = subMesh_dict[m][sm];
  83835. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83836. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83837. }
  83838. materialIndexOffset += ++materialMaxIndex;
  83839. }
  83840. }
  83841. return mesh;
  83842. };
  83843. // Build Mesh from CSG taking material and transforms into account
  83844. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83845. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83846. mesh.material = material;
  83847. mesh.position.copyFrom(this.position);
  83848. mesh.rotation.copyFrom(this.rotation);
  83849. if (this.rotationQuaternion) {
  83850. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83851. }
  83852. mesh.scaling.copyFrom(this.scaling);
  83853. mesh.computeWorldMatrix(true);
  83854. return mesh;
  83855. };
  83856. return CSG;
  83857. }());
  83858. BABYLON.CSG = CSG;
  83859. })(BABYLON || (BABYLON = {}));
  83860. //# sourceMappingURL=babylon.csg.js.map
  83861. var BABYLON;
  83862. (function (BABYLON) {
  83863. var LensFlare = /** @class */ (function () {
  83864. function LensFlare(size, position, color, imgUrl, system) {
  83865. this.size = size;
  83866. this.position = position;
  83867. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83868. this.color = color || new BABYLON.Color3(1, 1, 1);
  83869. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83870. this._system = system;
  83871. system.lensFlares.push(this);
  83872. }
  83873. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83874. return new LensFlare(size, position, color, imgUrl, system);
  83875. };
  83876. LensFlare.prototype.dispose = function () {
  83877. if (this.texture) {
  83878. this.texture.dispose();
  83879. }
  83880. // Remove from scene
  83881. var index = this._system.lensFlares.indexOf(this);
  83882. this._system.lensFlares.splice(index, 1);
  83883. };
  83884. ;
  83885. return LensFlare;
  83886. }());
  83887. BABYLON.LensFlare = LensFlare;
  83888. })(BABYLON || (BABYLON = {}));
  83889. //# sourceMappingURL=babylon.lensFlare.js.map
  83890. var BABYLON;
  83891. (function (BABYLON) {
  83892. // Adds the parser to the scene parsers.
  83893. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  83894. // Lens flares
  83895. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  83896. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  83897. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  83898. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  83899. container.lensFlareSystems.push(lf);
  83900. }
  83901. }
  83902. });
  83903. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  83904. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  83905. if (this.lensFlareSystems[index].name === name) {
  83906. return this.lensFlareSystems[index];
  83907. }
  83908. }
  83909. return null;
  83910. };
  83911. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  83912. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  83913. if (this.lensFlareSystems[index].id === id) {
  83914. return this.lensFlareSystems[index];
  83915. }
  83916. }
  83917. return null;
  83918. };
  83919. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  83920. var index = this.lensFlareSystems.indexOf(toRemove);
  83921. if (index !== -1) {
  83922. this.lensFlareSystems.splice(index, 1);
  83923. }
  83924. return index;
  83925. };
  83926. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  83927. this.lensFlareSystems.push(newLensFlareSystem);
  83928. };
  83929. /**
  83930. * Defines the layer scene component responsible to manage any layers
  83931. * in a given scene.
  83932. */
  83933. var LensFlareSystemSceneComponent = /** @class */ (function () {
  83934. /**
  83935. * Creates a new instance of the component for the given scene
  83936. * @param scene Defines the scene to register the component in
  83937. */
  83938. function LensFlareSystemSceneComponent(scene) {
  83939. /**
  83940. * The component name helpfull to identify the component in the list of scene components.
  83941. */
  83942. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  83943. this.scene = scene;
  83944. this._lensFlareSystems = scene.lensFlareSystems = new Array();
  83945. }
  83946. /**
  83947. * Registers the component in a given scene
  83948. */
  83949. LensFlareSystemSceneComponent.prototype.register = function () {
  83950. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  83951. };
  83952. /**
  83953. * Rebuilds the elements related to this component in case of
  83954. * context lost for instance.
  83955. */
  83956. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  83957. // Nothing to do for lens flare
  83958. };
  83959. /**
  83960. * Adds all the element from the container to the scene
  83961. * @param container the container holding the elements
  83962. */
  83963. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  83964. var _this = this;
  83965. if (!container.lensFlareSystems) {
  83966. return;
  83967. }
  83968. container.lensFlareSystems.forEach(function (o) {
  83969. _this.scene.addLensFlareSystem(o);
  83970. });
  83971. };
  83972. /**
  83973. * Removes all the elements in the container from the scene
  83974. * @param container contains the elements to remove
  83975. */
  83976. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  83977. var _this = this;
  83978. if (!container.lensFlareSystems) {
  83979. return;
  83980. }
  83981. container.lensFlareSystems.forEach(function (o) {
  83982. _this.scene.removeLensFlareSystem(o);
  83983. });
  83984. };
  83985. /**
  83986. * Serializes the component data to the specified json object
  83987. * @param serializationObject The object to serialize to
  83988. */
  83989. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  83990. // Lens flares
  83991. serializationObject.lensFlareSystems = [];
  83992. for (var _i = 0, _a = this._lensFlareSystems; _i < _a.length; _i++) {
  83993. var lensFlareSystem = _a[_i];
  83994. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  83995. }
  83996. };
  83997. /**
  83998. * Disposes the component and the associated ressources.
  83999. */
  84000. LensFlareSystemSceneComponent.prototype.dispose = function () {
  84001. while (this._lensFlareSystems.length) {
  84002. this._lensFlareSystems[0].dispose();
  84003. }
  84004. };
  84005. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  84006. // Lens flares
  84007. if (this.scene.lensFlaresEnabled) {
  84008. BABYLON.Tools.StartPerformanceCounter("Lens flares", this._lensFlareSystems.length > 0);
  84009. for (var _i = 0, _a = this._lensFlareSystems; _i < _a.length; _i++) {
  84010. var lensFlareSystem = _a[_i];
  84011. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  84012. lensFlareSystem.render();
  84013. }
  84014. }
  84015. BABYLON.Tools.EndPerformanceCounter("Lens flares", this._lensFlareSystems.length > 0);
  84016. }
  84017. };
  84018. return LensFlareSystemSceneComponent;
  84019. }());
  84020. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  84021. })(BABYLON || (BABYLON = {}));
  84022. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  84023. var BABYLON;
  84024. (function (BABYLON) {
  84025. var LensFlareSystem = /** @class */ (function () {
  84026. function LensFlareSystem(name, emitter, scene) {
  84027. this.name = name;
  84028. this.lensFlares = new Array();
  84029. this.borderLimit = 300;
  84030. this.viewportBorder = 0;
  84031. this.layerMask = 0x0FFFFFFF;
  84032. this._vertexBuffers = {};
  84033. this._isEnabled = true;
  84034. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84035. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  84036. if (!component) {
  84037. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  84038. scene._addComponent(component);
  84039. }
  84040. this._emitter = emitter;
  84041. this.id = name;
  84042. scene.lensFlareSystems.push(this);
  84043. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  84044. var engine = scene.getEngine();
  84045. // VBO
  84046. var vertices = [];
  84047. vertices.push(1, 1);
  84048. vertices.push(-1, 1);
  84049. vertices.push(-1, -1);
  84050. vertices.push(1, -1);
  84051. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84052. // Indices
  84053. var indices = [];
  84054. indices.push(0);
  84055. indices.push(1);
  84056. indices.push(2);
  84057. indices.push(0);
  84058. indices.push(2);
  84059. indices.push(3);
  84060. this._indexBuffer = engine.createIndexBuffer(indices);
  84061. // Effects
  84062. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  84063. }
  84064. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  84065. get: function () {
  84066. return this._isEnabled;
  84067. },
  84068. set: function (value) {
  84069. this._isEnabled = value;
  84070. },
  84071. enumerable: true,
  84072. configurable: true
  84073. });
  84074. LensFlareSystem.prototype.getScene = function () {
  84075. return this._scene;
  84076. };
  84077. LensFlareSystem.prototype.getEmitter = function () {
  84078. return this._emitter;
  84079. };
  84080. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  84081. this._emitter = newEmitter;
  84082. };
  84083. LensFlareSystem.prototype.getEmitterPosition = function () {
  84084. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  84085. };
  84086. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  84087. var position = this.getEmitterPosition();
  84088. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  84089. this._positionX = position.x;
  84090. this._positionY = position.y;
  84091. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  84092. if (this.viewportBorder > 0) {
  84093. globalViewport.x -= this.viewportBorder;
  84094. globalViewport.y -= this.viewportBorder;
  84095. globalViewport.width += this.viewportBorder * 2;
  84096. globalViewport.height += this.viewportBorder * 2;
  84097. position.x += this.viewportBorder;
  84098. position.y += this.viewportBorder;
  84099. this._positionX += this.viewportBorder;
  84100. this._positionY += this.viewportBorder;
  84101. }
  84102. if (position.z > 0) {
  84103. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  84104. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  84105. return true;
  84106. }
  84107. return true;
  84108. }
  84109. return false;
  84110. };
  84111. LensFlareSystem.prototype._isVisible = function () {
  84112. if (!this._isEnabled || !this._scene.activeCamera) {
  84113. return false;
  84114. }
  84115. var emitterPosition = this.getEmitterPosition();
  84116. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84117. var distance = direction.length();
  84118. direction.normalize();
  84119. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84120. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84121. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84122. };
  84123. LensFlareSystem.prototype.render = function () {
  84124. if (!this._effect.isReady() || !this._scene.activeCamera)
  84125. return false;
  84126. var engine = this._scene.getEngine();
  84127. var viewport = this._scene.activeCamera.viewport;
  84128. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84129. // Position
  84130. if (!this.computeEffectivePosition(globalViewport)) {
  84131. return false;
  84132. }
  84133. // Visibility
  84134. if (!this._isVisible()) {
  84135. return false;
  84136. }
  84137. // Intensity
  84138. var awayX;
  84139. var awayY;
  84140. if (this._positionX < this.borderLimit + globalViewport.x) {
  84141. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84142. }
  84143. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84144. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84145. }
  84146. else {
  84147. awayX = 0;
  84148. }
  84149. if (this._positionY < this.borderLimit + globalViewport.y) {
  84150. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84151. }
  84152. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84153. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84154. }
  84155. else {
  84156. awayY = 0;
  84157. }
  84158. var away = (awayX > awayY) ? awayX : awayY;
  84159. away -= this.viewportBorder;
  84160. if (away > this.borderLimit) {
  84161. away = this.borderLimit;
  84162. }
  84163. var intensity = 1.0 - (away / this.borderLimit);
  84164. if (intensity < 0) {
  84165. return false;
  84166. }
  84167. if (intensity > 1.0) {
  84168. intensity = 1.0;
  84169. }
  84170. if (this.viewportBorder > 0) {
  84171. globalViewport.x += this.viewportBorder;
  84172. globalViewport.y += this.viewportBorder;
  84173. globalViewport.width -= this.viewportBorder * 2;
  84174. globalViewport.height -= this.viewportBorder * 2;
  84175. this._positionX -= this.viewportBorder;
  84176. this._positionY -= this.viewportBorder;
  84177. }
  84178. // Position
  84179. var centerX = globalViewport.x + globalViewport.width / 2;
  84180. var centerY = globalViewport.y + globalViewport.height / 2;
  84181. var distX = centerX - this._positionX;
  84182. var distY = centerY - this._positionY;
  84183. // Effects
  84184. engine.enableEffect(this._effect);
  84185. engine.setState(false);
  84186. engine.setDepthBuffer(false);
  84187. // VBOs
  84188. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84189. // Flares
  84190. for (var index = 0; index < this.lensFlares.length; index++) {
  84191. var flare = this.lensFlares[index];
  84192. engine.setAlphaMode(flare.alphaMode);
  84193. var x = centerX - (distX * flare.position);
  84194. var y = centerY - (distY * flare.position);
  84195. var cw = flare.size;
  84196. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84197. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84198. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84199. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84200. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84201. // Texture
  84202. this._effect.setTexture("textureSampler", flare.texture);
  84203. // Color
  84204. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84205. // Draw order
  84206. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84207. }
  84208. engine.setDepthBuffer(true);
  84209. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84210. return true;
  84211. };
  84212. LensFlareSystem.prototype.dispose = function () {
  84213. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84214. if (vertexBuffer) {
  84215. vertexBuffer.dispose();
  84216. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84217. }
  84218. if (this._indexBuffer) {
  84219. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84220. this._indexBuffer = null;
  84221. }
  84222. while (this.lensFlares.length) {
  84223. this.lensFlares[0].dispose();
  84224. }
  84225. // Remove from scene
  84226. var index = this._scene.lensFlareSystems.indexOf(this);
  84227. this._scene.lensFlareSystems.splice(index, 1);
  84228. };
  84229. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84230. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84231. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84232. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84233. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84234. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84235. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84236. var parsedFlare = parsedLensFlareSystem.flares[index];
  84237. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84238. }
  84239. return lensFlareSystem;
  84240. };
  84241. LensFlareSystem.prototype.serialize = function () {
  84242. var serializationObject = {};
  84243. serializationObject.id = this.id;
  84244. serializationObject.name = this.name;
  84245. serializationObject.emitterId = this.getEmitter().id;
  84246. serializationObject.borderLimit = this.borderLimit;
  84247. serializationObject.flares = [];
  84248. for (var index = 0; index < this.lensFlares.length; index++) {
  84249. var flare = this.lensFlares[index];
  84250. serializationObject.flares.push({
  84251. size: flare.size,
  84252. position: flare.position,
  84253. color: flare.color.asArray(),
  84254. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84255. });
  84256. }
  84257. return serializationObject;
  84258. };
  84259. return LensFlareSystem;
  84260. }());
  84261. BABYLON.LensFlareSystem = LensFlareSystem;
  84262. })(BABYLON || (BABYLON = {}));
  84263. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84264. var BABYLON;
  84265. (function (BABYLON) {
  84266. /**
  84267. * This is a holder class for the physics joint created by the physics plugin.
  84268. * It holds a set of functions to control the underlying joint.
  84269. */
  84270. var PhysicsJoint = /** @class */ (function () {
  84271. function PhysicsJoint(type, jointData) {
  84272. this.type = type;
  84273. this.jointData = jointData;
  84274. jointData.nativeParams = jointData.nativeParams || {};
  84275. }
  84276. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84277. get: function () {
  84278. return this._physicsJoint;
  84279. },
  84280. set: function (newJoint) {
  84281. if (this._physicsJoint) {
  84282. //remove from the wolrd
  84283. }
  84284. this._physicsJoint = newJoint;
  84285. },
  84286. enumerable: true,
  84287. configurable: true
  84288. });
  84289. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84290. set: function (physicsPlugin) {
  84291. this._physicsPlugin = physicsPlugin;
  84292. },
  84293. enumerable: true,
  84294. configurable: true
  84295. });
  84296. /**
  84297. * Execute a function that is physics-plugin specific.
  84298. * @param {Function} func the function that will be executed.
  84299. * It accepts two parameters: the physics world and the physics joint.
  84300. */
  84301. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84302. func(this._physicsPlugin.world, this._physicsJoint);
  84303. };
  84304. //TODO check if the native joints are the same
  84305. //Joint Types
  84306. PhysicsJoint.DistanceJoint = 0;
  84307. PhysicsJoint.HingeJoint = 1;
  84308. PhysicsJoint.BallAndSocketJoint = 2;
  84309. PhysicsJoint.WheelJoint = 3;
  84310. PhysicsJoint.SliderJoint = 4;
  84311. //OIMO
  84312. PhysicsJoint.PrismaticJoint = 5;
  84313. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84314. PhysicsJoint.UniversalJoint = 6;
  84315. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84316. //Cannon
  84317. //Similar to a Ball-Joint. Different in params
  84318. PhysicsJoint.PointToPointJoint = 8;
  84319. //Cannon only at the moment
  84320. PhysicsJoint.SpringJoint = 9;
  84321. PhysicsJoint.LockJoint = 10;
  84322. return PhysicsJoint;
  84323. }());
  84324. BABYLON.PhysicsJoint = PhysicsJoint;
  84325. /**
  84326. * A class representing a physics distance joint.
  84327. */
  84328. var DistanceJoint = /** @class */ (function (_super) {
  84329. __extends(DistanceJoint, _super);
  84330. function DistanceJoint(jointData) {
  84331. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84332. }
  84333. /**
  84334. * Update the predefined distance.
  84335. */
  84336. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84337. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84338. };
  84339. return DistanceJoint;
  84340. }(PhysicsJoint));
  84341. BABYLON.DistanceJoint = DistanceJoint;
  84342. var MotorEnabledJoint = /** @class */ (function (_super) {
  84343. __extends(MotorEnabledJoint, _super);
  84344. function MotorEnabledJoint(type, jointData) {
  84345. return _super.call(this, type, jointData) || this;
  84346. }
  84347. /**
  84348. * Set the motor values.
  84349. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84350. * @param {number} force the force to apply
  84351. * @param {number} maxForce max force for this motor.
  84352. */
  84353. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84354. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84355. };
  84356. /**
  84357. * Set the motor's limits.
  84358. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84359. */
  84360. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84361. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84362. };
  84363. return MotorEnabledJoint;
  84364. }(PhysicsJoint));
  84365. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84366. /**
  84367. * This class represents a single hinge physics joint
  84368. */
  84369. var HingeJoint = /** @class */ (function (_super) {
  84370. __extends(HingeJoint, _super);
  84371. function HingeJoint(jointData) {
  84372. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84373. }
  84374. /**
  84375. * Set the motor values.
  84376. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84377. * @param {number} force the force to apply
  84378. * @param {number} maxForce max force for this motor.
  84379. */
  84380. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84381. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84382. };
  84383. /**
  84384. * Set the motor's limits.
  84385. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84386. */
  84387. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84388. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84389. };
  84390. return HingeJoint;
  84391. }(MotorEnabledJoint));
  84392. BABYLON.HingeJoint = HingeJoint;
  84393. /**
  84394. * This class represents a dual hinge physics joint (same as wheel joint)
  84395. */
  84396. var Hinge2Joint = /** @class */ (function (_super) {
  84397. __extends(Hinge2Joint, _super);
  84398. function Hinge2Joint(jointData) {
  84399. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84400. }
  84401. /**
  84402. * Set the motor values.
  84403. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84404. * @param {number} force the force to apply
  84405. * @param {number} maxForce max force for this motor.
  84406. * @param {motorIndex} the motor's index, 0 or 1.
  84407. */
  84408. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84409. if (motorIndex === void 0) { motorIndex = 0; }
  84410. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84411. };
  84412. /**
  84413. * Set the motor limits.
  84414. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84415. * @param {number} upperLimit the upper limit
  84416. * @param {number} lowerLimit lower limit
  84417. * @param {motorIndex} the motor's index, 0 or 1.
  84418. */
  84419. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84420. if (motorIndex === void 0) { motorIndex = 0; }
  84421. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84422. };
  84423. return Hinge2Joint;
  84424. }(MotorEnabledJoint));
  84425. BABYLON.Hinge2Joint = Hinge2Joint;
  84426. })(BABYLON || (BABYLON = {}));
  84427. //# sourceMappingURL=babylon.physicsJoint.js.map
  84428. var BABYLON;
  84429. (function (BABYLON) {
  84430. var PhysicsImpostor = /** @class */ (function () {
  84431. function PhysicsImpostor(object, type, _options, _scene) {
  84432. if (_options === void 0) { _options = { mass: 0 }; }
  84433. var _this = this;
  84434. this.object = object;
  84435. this.type = type;
  84436. this._options = _options;
  84437. this._scene = _scene;
  84438. this._bodyUpdateRequired = false;
  84439. this._onBeforePhysicsStepCallbacks = new Array();
  84440. this._onAfterPhysicsStepCallbacks = new Array();
  84441. this._onPhysicsCollideCallbacks = [];
  84442. this._deltaPosition = BABYLON.Vector3.Zero();
  84443. this._isDisposed = false;
  84444. //temp variables for parent rotation calculations
  84445. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84446. this._tmpQuat = new BABYLON.Quaternion();
  84447. this._tmpQuat2 = new BABYLON.Quaternion();
  84448. /**
  84449. * this function is executed by the physics engine.
  84450. */
  84451. this.beforeStep = function () {
  84452. if (!_this._physicsEngine) {
  84453. return;
  84454. }
  84455. _this.object.translate(_this._deltaPosition, -1);
  84456. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84457. _this.object.computeWorldMatrix(false);
  84458. if (_this.object.parent && _this.object.rotationQuaternion) {
  84459. _this.getParentsRotation();
  84460. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84461. }
  84462. else {
  84463. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84464. }
  84465. if (!_this._options.disableBidirectionalTransformation) {
  84466. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84467. }
  84468. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84469. func(_this);
  84470. });
  84471. };
  84472. /**
  84473. * this function is executed by the physics engine.
  84474. */
  84475. this.afterStep = function () {
  84476. if (!_this._physicsEngine) {
  84477. return;
  84478. }
  84479. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84480. func(_this);
  84481. });
  84482. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84483. // object has now its world rotation. needs to be converted to local.
  84484. if (_this.object.parent && _this.object.rotationQuaternion) {
  84485. _this.getParentsRotation();
  84486. _this._tmpQuat.conjugateInPlace();
  84487. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84488. }
  84489. // take the position set and make it the absolute position of this object.
  84490. _this.object.setAbsolutePosition(_this.object.position);
  84491. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84492. _this.object.translate(_this._deltaPosition, 1);
  84493. };
  84494. /**
  84495. * Legacy collision detection event support
  84496. */
  84497. this.onCollideEvent = null;
  84498. //event and body object due to cannon's event-based architecture.
  84499. this.onCollide = function (e) {
  84500. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84501. return;
  84502. }
  84503. if (!_this._physicsEngine) {
  84504. return;
  84505. }
  84506. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84507. if (otherImpostor) {
  84508. // Legacy collision detection event support
  84509. if (_this.onCollideEvent) {
  84510. _this.onCollideEvent(_this, otherImpostor);
  84511. }
  84512. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84513. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84514. }).forEach(function (obj) {
  84515. obj.callback(_this, otherImpostor);
  84516. });
  84517. }
  84518. };
  84519. //sanity check!
  84520. if (!this.object) {
  84521. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84522. return;
  84523. }
  84524. //legacy support for old syntax.
  84525. if (!this._scene && object.getScene) {
  84526. this._scene = object.getScene();
  84527. }
  84528. if (!this._scene) {
  84529. return;
  84530. }
  84531. this._physicsEngine = this._scene.getPhysicsEngine();
  84532. if (!this._physicsEngine) {
  84533. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84534. }
  84535. else {
  84536. //set the object's quaternion, if not set
  84537. if (!this.object.rotationQuaternion) {
  84538. if (this.object.rotation) {
  84539. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84540. }
  84541. else {
  84542. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84543. }
  84544. }
  84545. //default options params
  84546. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84547. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84548. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84549. this._joints = [];
  84550. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84551. if (!this.object.parent || this._options.ignoreParent) {
  84552. this._init();
  84553. }
  84554. else if (this.object.parent.physicsImpostor) {
  84555. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84556. }
  84557. }
  84558. }
  84559. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84560. get: function () {
  84561. return this._isDisposed;
  84562. },
  84563. enumerable: true,
  84564. configurable: true
  84565. });
  84566. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84567. get: function () {
  84568. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84569. },
  84570. set: function (value) {
  84571. this.setMass(value);
  84572. },
  84573. enumerable: true,
  84574. configurable: true
  84575. });
  84576. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84577. get: function () {
  84578. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84579. },
  84580. set: function (value) {
  84581. if (!this._physicsEngine) {
  84582. return;
  84583. }
  84584. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84585. },
  84586. enumerable: true,
  84587. configurable: true
  84588. });
  84589. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84590. get: function () {
  84591. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84592. },
  84593. set: function (value) {
  84594. if (!this._physicsEngine) {
  84595. return;
  84596. }
  84597. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84598. },
  84599. enumerable: true,
  84600. configurable: true
  84601. });
  84602. /**
  84603. * This function will completly initialize this impostor.
  84604. * It will create a new body - but only if this mesh has no parent.
  84605. * If it has, this impostor will not be used other than to define the impostor
  84606. * of the child mesh.
  84607. */
  84608. PhysicsImpostor.prototype._init = function () {
  84609. if (!this._physicsEngine) {
  84610. return;
  84611. }
  84612. this._physicsEngine.removeImpostor(this);
  84613. this.physicsBody = null;
  84614. this._parent = this._parent || this._getPhysicsParent();
  84615. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84616. this._physicsEngine.addImpostor(this);
  84617. }
  84618. };
  84619. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84620. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84621. var parentMesh = this.object.parent;
  84622. return parentMesh.physicsImpostor;
  84623. }
  84624. return null;
  84625. };
  84626. /**
  84627. * Should a new body be generated.
  84628. */
  84629. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84630. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84631. };
  84632. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84633. this.forceUpdate();
  84634. };
  84635. /**
  84636. * Force a regeneration of this or the parent's impostor's body.
  84637. * Use under cautious - This will remove all joints already implemented.
  84638. */
  84639. PhysicsImpostor.prototype.forceUpdate = function () {
  84640. this._init();
  84641. if (this.parent && !this._options.ignoreParent) {
  84642. this.parent.forceUpdate();
  84643. }
  84644. };
  84645. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84646. /*public get mesh(): AbstractMesh {
  84647. return this._mesh;
  84648. }*/
  84649. /**
  84650. * Gets the body that holds this impostor. Either its own, or its parent.
  84651. */
  84652. get: function () {
  84653. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84654. },
  84655. /**
  84656. * Set the physics body. Used mainly by the physics engine/plugin
  84657. */
  84658. set: function (physicsBody) {
  84659. if (this._physicsBody && this._physicsEngine) {
  84660. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84661. }
  84662. this._physicsBody = physicsBody;
  84663. this.resetUpdateFlags();
  84664. },
  84665. enumerable: true,
  84666. configurable: true
  84667. });
  84668. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84669. get: function () {
  84670. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84671. },
  84672. set: function (value) {
  84673. this._parent = value;
  84674. },
  84675. enumerable: true,
  84676. configurable: true
  84677. });
  84678. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84679. this._bodyUpdateRequired = false;
  84680. };
  84681. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84682. if (this.object.getBoundingInfo) {
  84683. var q = this.object.rotationQuaternion;
  84684. //reset rotation
  84685. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84686. //calculate the world matrix with no rotation
  84687. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84688. var boundingInfo = this.object.getBoundingInfo();
  84689. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84690. //bring back the rotation
  84691. this.object.rotationQuaternion = q;
  84692. //calculate the world matrix with the new rotation
  84693. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84694. return size;
  84695. }
  84696. else {
  84697. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84698. }
  84699. };
  84700. PhysicsImpostor.prototype.getObjectCenter = function () {
  84701. if (this.object.getBoundingInfo) {
  84702. var boundingInfo = this.object.getBoundingInfo();
  84703. return boundingInfo.boundingBox.centerWorld;
  84704. }
  84705. else {
  84706. return this.object.position;
  84707. }
  84708. };
  84709. /**
  84710. * Get a specific parametes from the options parameter.
  84711. */
  84712. PhysicsImpostor.prototype.getParam = function (paramName) {
  84713. return this._options[paramName];
  84714. };
  84715. /**
  84716. * Sets a specific parameter in the options given to the physics plugin
  84717. */
  84718. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84719. this._options[paramName] = value;
  84720. this._bodyUpdateRequired = true;
  84721. };
  84722. /**
  84723. * Specifically change the body's mass option. Won't recreate the physics body object
  84724. */
  84725. PhysicsImpostor.prototype.setMass = function (mass) {
  84726. if (this.getParam("mass") !== mass) {
  84727. this.setParam("mass", mass);
  84728. }
  84729. if (this._physicsEngine) {
  84730. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84731. }
  84732. };
  84733. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84734. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84735. };
  84736. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84737. if (this._physicsEngine) {
  84738. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84739. }
  84740. };
  84741. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84742. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84743. };
  84744. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84745. if (this._physicsEngine) {
  84746. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84747. }
  84748. };
  84749. /**
  84750. * Execute a function with the physics plugin native code.
  84751. * Provide a function the will have two variables - the world object and the physics body object.
  84752. */
  84753. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84754. if (this._physicsEngine) {
  84755. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84756. }
  84757. };
  84758. /**
  84759. * Register a function that will be executed before the physics world is stepping forward.
  84760. */
  84761. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84762. this._onBeforePhysicsStepCallbacks.push(func);
  84763. };
  84764. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84765. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84766. if (index > -1) {
  84767. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84768. }
  84769. else {
  84770. BABYLON.Tools.Warn("Function to remove was not found");
  84771. }
  84772. };
  84773. /**
  84774. * Register a function that will be executed after the physics step
  84775. */
  84776. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84777. this._onAfterPhysicsStepCallbacks.push(func);
  84778. };
  84779. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84780. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84781. if (index > -1) {
  84782. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84783. }
  84784. else {
  84785. BABYLON.Tools.Warn("Function to remove was not found");
  84786. }
  84787. };
  84788. /**
  84789. * register a function that will be executed when this impostor collides against a different body.
  84790. */
  84791. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84792. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84793. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84794. };
  84795. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84796. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84797. var index = -1;
  84798. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84799. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84800. // chcek the arrays match
  84801. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84802. return collidedAgainstList.indexOf(impostor) > -1;
  84803. });
  84804. if (sameList) {
  84805. index = idx;
  84806. }
  84807. return sameList;
  84808. }
  84809. return false;
  84810. });
  84811. if (found) {
  84812. this._onPhysicsCollideCallbacks.splice(index, 1);
  84813. }
  84814. else {
  84815. BABYLON.Tools.Warn("Function to remove was not found");
  84816. }
  84817. };
  84818. PhysicsImpostor.prototype.getParentsRotation = function () {
  84819. var parent = this.object.parent;
  84820. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84821. while (parent) {
  84822. if (parent.rotationQuaternion) {
  84823. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84824. }
  84825. else {
  84826. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84827. }
  84828. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84829. parent = parent.parent;
  84830. }
  84831. return this._tmpQuat;
  84832. };
  84833. /**
  84834. * Apply a force
  84835. */
  84836. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84837. if (this._physicsEngine) {
  84838. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84839. }
  84840. return this;
  84841. };
  84842. /**
  84843. * Apply an impulse
  84844. */
  84845. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84846. if (this._physicsEngine) {
  84847. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84848. }
  84849. return this;
  84850. };
  84851. /**
  84852. * A help function to create a joint.
  84853. */
  84854. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84855. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84856. this.addJoint(otherImpostor, joint);
  84857. return this;
  84858. };
  84859. /**
  84860. * Add a joint to this impostor with a different impostor.
  84861. */
  84862. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84863. this._joints.push({
  84864. otherImpostor: otherImpostor,
  84865. joint: joint
  84866. });
  84867. if (this._physicsEngine) {
  84868. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84869. }
  84870. return this;
  84871. };
  84872. /**
  84873. * Will keep this body still, in a sleep mode.
  84874. */
  84875. PhysicsImpostor.prototype.sleep = function () {
  84876. if (this._physicsEngine) {
  84877. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84878. }
  84879. return this;
  84880. };
  84881. /**
  84882. * Wake the body up.
  84883. */
  84884. PhysicsImpostor.prototype.wakeUp = function () {
  84885. if (this._physicsEngine) {
  84886. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84887. }
  84888. return this;
  84889. };
  84890. PhysicsImpostor.prototype.clone = function (newObject) {
  84891. if (!newObject)
  84892. return null;
  84893. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84894. };
  84895. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84896. var _this = this;
  84897. //no dispose if no physics engine is available.
  84898. if (!this._physicsEngine) {
  84899. return;
  84900. }
  84901. this._joints.forEach(function (j) {
  84902. if (_this._physicsEngine) {
  84903. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84904. }
  84905. });
  84906. //dispose the physics body
  84907. this._physicsEngine.removeImpostor(this);
  84908. if (this.parent) {
  84909. this.parent.forceUpdate();
  84910. }
  84911. else {
  84912. /*this._object.getChildMeshes().forEach(function(mesh) {
  84913. if (mesh.physicsImpostor) {
  84914. if (disposeChildren) {
  84915. mesh.physicsImpostor.dispose();
  84916. mesh.physicsImpostor = null;
  84917. }
  84918. }
  84919. })*/
  84920. }
  84921. this._isDisposed = true;
  84922. };
  84923. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  84924. this._deltaPosition.copyFrom(position);
  84925. };
  84926. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  84927. if (!this._deltaRotation) {
  84928. this._deltaRotation = new BABYLON.Quaternion();
  84929. }
  84930. this._deltaRotation.copyFrom(rotation);
  84931. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  84932. };
  84933. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  84934. if (this._physicsEngine) {
  84935. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  84936. }
  84937. return this;
  84938. };
  84939. PhysicsImpostor.prototype.getRadius = function () {
  84940. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84941. };
  84942. /**
  84943. * Sync a bone with this impostor
  84944. * @param bone The bone to sync to the impostor.
  84945. * @param boneMesh The mesh that the bone is influencing.
  84946. * @param jointPivot The pivot of the joint / bone in local space.
  84947. * @param distToJoint Optional distance from the impostor to the joint.
  84948. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84949. */
  84950. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  84951. var tempVec = PhysicsImpostor._tmpVecs[0];
  84952. var mesh = this.object;
  84953. if (mesh.rotationQuaternion) {
  84954. if (adjustRotation) {
  84955. var tempQuat = PhysicsImpostor._tmpQuat;
  84956. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  84957. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  84958. }
  84959. else {
  84960. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  84961. }
  84962. }
  84963. tempVec.x = 0;
  84964. tempVec.y = 0;
  84965. tempVec.z = 0;
  84966. if (jointPivot) {
  84967. tempVec.x = jointPivot.x;
  84968. tempVec.y = jointPivot.y;
  84969. tempVec.z = jointPivot.z;
  84970. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  84971. if (distToJoint === undefined || distToJoint === null) {
  84972. distToJoint = jointPivot.length();
  84973. }
  84974. tempVec.x *= distToJoint;
  84975. tempVec.y *= distToJoint;
  84976. tempVec.z *= distToJoint;
  84977. }
  84978. if (bone.getParent()) {
  84979. tempVec.addInPlace(mesh.getAbsolutePosition());
  84980. bone.setAbsolutePosition(tempVec, boneMesh);
  84981. }
  84982. else {
  84983. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  84984. boneMesh.position.x -= tempVec.x;
  84985. boneMesh.position.y -= tempVec.y;
  84986. boneMesh.position.z -= tempVec.z;
  84987. }
  84988. };
  84989. /**
  84990. * Sync impostor to a bone
  84991. * @param bone The bone that the impostor will be synced to.
  84992. * @param boneMesh The mesh that the bone is influencing.
  84993. * @param jointPivot The pivot of the joint / bone in local space.
  84994. * @param distToJoint Optional distance from the impostor to the joint.
  84995. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84996. * @param boneAxis Optional vector3 axis the bone is aligned with
  84997. */
  84998. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  84999. var mesh = this.object;
  85000. if (mesh.rotationQuaternion) {
  85001. if (adjustRotation) {
  85002. var tempQuat = PhysicsImpostor._tmpQuat;
  85003. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  85004. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  85005. }
  85006. else {
  85007. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  85008. }
  85009. }
  85010. var pos = PhysicsImpostor._tmpVecs[0];
  85011. var boneDir = PhysicsImpostor._tmpVecs[1];
  85012. if (!boneAxis) {
  85013. boneAxis = PhysicsImpostor._tmpVecs[2];
  85014. boneAxis.x = 0;
  85015. boneAxis.y = 1;
  85016. boneAxis.z = 0;
  85017. }
  85018. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  85019. bone.getAbsolutePositionToRef(boneMesh, pos);
  85020. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  85021. distToJoint = jointPivot.length();
  85022. }
  85023. if (distToJoint !== undefined && distToJoint !== null) {
  85024. pos.x += boneDir.x * distToJoint;
  85025. pos.y += boneDir.y * distToJoint;
  85026. pos.z += boneDir.z * distToJoint;
  85027. }
  85028. mesh.setAbsolutePosition(pos);
  85029. };
  85030. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  85031. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  85032. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85033. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  85034. //Impostor types
  85035. PhysicsImpostor.NoImpostor = 0;
  85036. PhysicsImpostor.SphereImpostor = 1;
  85037. PhysicsImpostor.BoxImpostor = 2;
  85038. PhysicsImpostor.PlaneImpostor = 3;
  85039. PhysicsImpostor.MeshImpostor = 4;
  85040. PhysicsImpostor.CylinderImpostor = 7;
  85041. PhysicsImpostor.ParticleImpostor = 8;
  85042. PhysicsImpostor.HeightmapImpostor = 9;
  85043. return PhysicsImpostor;
  85044. }());
  85045. BABYLON.PhysicsImpostor = PhysicsImpostor;
  85046. })(BABYLON || (BABYLON = {}));
  85047. //# sourceMappingURL=babylon.physicsImpostor.js.map
  85048. var BABYLON;
  85049. (function (BABYLON) {
  85050. var PhysicsEngine = /** @class */ (function () {
  85051. function PhysicsEngine(gravity, _physicsPlugin) {
  85052. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  85053. this._physicsPlugin = _physicsPlugin;
  85054. //new methods and parameters
  85055. this._impostors = [];
  85056. this._joints = [];
  85057. if (!this._physicsPlugin.isSupported()) {
  85058. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  85059. + "Please make sure it is included.");
  85060. }
  85061. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  85062. this.setGravity(gravity);
  85063. this.setTimeStep();
  85064. }
  85065. PhysicsEngine.prototype.setGravity = function (gravity) {
  85066. this.gravity = gravity;
  85067. this._physicsPlugin.setGravity(this.gravity);
  85068. };
  85069. /**
  85070. * Set the time step of the physics engine.
  85071. * default is 1/60.
  85072. * To slow it down, enter 1/600 for example.
  85073. * To speed it up, 1/30
  85074. * @param {number} newTimeStep the new timestep to apply to this world.
  85075. */
  85076. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  85077. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  85078. this._physicsPlugin.setTimeStep(newTimeStep);
  85079. };
  85080. /**
  85081. * Get the time step of the physics engine.
  85082. */
  85083. PhysicsEngine.prototype.getTimeStep = function () {
  85084. return this._physicsPlugin.getTimeStep();
  85085. };
  85086. PhysicsEngine.prototype.dispose = function () {
  85087. this._impostors.forEach(function (impostor) {
  85088. impostor.dispose();
  85089. });
  85090. this._physicsPlugin.dispose();
  85091. };
  85092. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  85093. return this._physicsPlugin.name;
  85094. };
  85095. /**
  85096. * Adding a new impostor for the impostor tracking.
  85097. * This will be done by the impostor itself.
  85098. * @param {PhysicsImpostor} impostor the impostor to add
  85099. */
  85100. PhysicsEngine.prototype.addImpostor = function (impostor) {
  85101. impostor.uniqueId = this._impostors.push(impostor);
  85102. //if no parent, generate the body
  85103. if (!impostor.parent) {
  85104. this._physicsPlugin.generatePhysicsBody(impostor);
  85105. }
  85106. };
  85107. /**
  85108. * Remove an impostor from the engine.
  85109. * This impostor and its mesh will not longer be updated by the physics engine.
  85110. * @param {PhysicsImpostor} impostor the impostor to remove
  85111. */
  85112. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85113. var index = this._impostors.indexOf(impostor);
  85114. if (index > -1) {
  85115. var removed = this._impostors.splice(index, 1);
  85116. //Is it needed?
  85117. if (removed.length) {
  85118. //this will also remove it from the world.
  85119. removed[0].physicsBody = null;
  85120. }
  85121. }
  85122. };
  85123. /**
  85124. * Add a joint to the physics engine
  85125. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85126. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85127. * @param {PhysicsJoint} the joint that will connect both impostors.
  85128. */
  85129. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85130. var impostorJoint = {
  85131. mainImpostor: mainImpostor,
  85132. connectedImpostor: connectedImpostor,
  85133. joint: joint
  85134. };
  85135. joint.physicsPlugin = this._physicsPlugin;
  85136. this._joints.push(impostorJoint);
  85137. this._physicsPlugin.generateJoint(impostorJoint);
  85138. };
  85139. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85140. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85141. return (impostorJoint.connectedImpostor === connectedImpostor
  85142. && impostorJoint.joint === joint
  85143. && impostorJoint.mainImpostor === mainImpostor);
  85144. });
  85145. if (matchingJoints.length) {
  85146. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85147. //TODO remove it from the list as well
  85148. }
  85149. };
  85150. /**
  85151. * Called by the scene. no need to call it.
  85152. */
  85153. PhysicsEngine.prototype._step = function (delta) {
  85154. var _this = this;
  85155. //check if any mesh has no body / requires an update
  85156. this._impostors.forEach(function (impostor) {
  85157. if (impostor.isBodyInitRequired()) {
  85158. _this._physicsPlugin.generatePhysicsBody(impostor);
  85159. }
  85160. });
  85161. if (delta > 0.1) {
  85162. delta = 0.1;
  85163. }
  85164. else if (delta <= 0) {
  85165. delta = 1.0 / 60.0;
  85166. }
  85167. this._physicsPlugin.executeStep(delta, this._impostors);
  85168. };
  85169. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85170. return this._physicsPlugin;
  85171. };
  85172. PhysicsEngine.prototype.getImpostors = function () {
  85173. return this._impostors;
  85174. };
  85175. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85176. for (var i = 0; i < this._impostors.length; ++i) {
  85177. if (this._impostors[i].object === object) {
  85178. return this._impostors[i];
  85179. }
  85180. }
  85181. return null;
  85182. };
  85183. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85184. for (var i = 0; i < this._impostors.length; ++i) {
  85185. if (this._impostors[i].physicsBody === body) {
  85186. return this._impostors[i];
  85187. }
  85188. }
  85189. return null;
  85190. };
  85191. // Statics
  85192. PhysicsEngine.Epsilon = 0.001;
  85193. return PhysicsEngine;
  85194. }());
  85195. BABYLON.PhysicsEngine = PhysicsEngine;
  85196. })(BABYLON || (BABYLON = {}));
  85197. //# sourceMappingURL=babylon.physicsEngine.js.map
  85198. var BABYLON;
  85199. (function (BABYLON) {
  85200. var PhysicsHelper = /** @class */ (function () {
  85201. function PhysicsHelper(scene) {
  85202. this._scene = scene;
  85203. this._physicsEngine = this._scene.getPhysicsEngine();
  85204. if (!this._physicsEngine) {
  85205. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85206. }
  85207. }
  85208. /**
  85209. * @param {Vector3} origin the origin of the explosion
  85210. * @param {number} radius the explosion radius
  85211. * @param {number} strength the explosion strength
  85212. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85213. */
  85214. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85215. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85216. if (!this._physicsEngine) {
  85217. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85218. return null;
  85219. }
  85220. var impostors = this._physicsEngine.getImpostors();
  85221. if (impostors.length === 0) {
  85222. return null;
  85223. }
  85224. var event = new PhysicsRadialExplosionEvent(this._scene);
  85225. impostors.forEach(function (impostor) {
  85226. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85227. if (!impostorForceAndContactPoint) {
  85228. return;
  85229. }
  85230. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85231. });
  85232. event.dispose(false);
  85233. return event;
  85234. };
  85235. /**
  85236. * @param {Vector3} origin the origin of the explosion
  85237. * @param {number} radius the explosion radius
  85238. * @param {number} strength the explosion strength
  85239. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85240. */
  85241. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85242. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85243. if (!this._physicsEngine) {
  85244. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85245. return null;
  85246. }
  85247. var impostors = this._physicsEngine.getImpostors();
  85248. if (impostors.length === 0) {
  85249. return null;
  85250. }
  85251. var event = new PhysicsRadialExplosionEvent(this._scene);
  85252. impostors.forEach(function (impostor) {
  85253. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85254. if (!impostorForceAndContactPoint) {
  85255. return;
  85256. }
  85257. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85258. });
  85259. event.dispose(false);
  85260. return event;
  85261. };
  85262. /**
  85263. * @param {Vector3} origin the origin of the explosion
  85264. * @param {number} radius the explosion radius
  85265. * @param {number} strength the explosion strength
  85266. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85267. */
  85268. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85269. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85270. if (!this._physicsEngine) {
  85271. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85272. return null;
  85273. }
  85274. var impostors = this._physicsEngine.getImpostors();
  85275. if (impostors.length === 0) {
  85276. return null;
  85277. }
  85278. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85279. event.dispose(false);
  85280. return event;
  85281. };
  85282. /**
  85283. * @param {Vector3} origin the origin of the updraft
  85284. * @param {number} radius the radius of the updraft
  85285. * @param {number} strength the strength of the updraft
  85286. * @param {number} height the height of the updraft
  85287. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85288. */
  85289. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85290. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85291. if (!this._physicsEngine) {
  85292. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85293. return null;
  85294. }
  85295. if (this._physicsEngine.getImpostors().length === 0) {
  85296. return null;
  85297. }
  85298. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85299. event.dispose(false);
  85300. return event;
  85301. };
  85302. /**
  85303. * @param {Vector3} origin the of the vortex
  85304. * @param {number} radius the radius of the vortex
  85305. * @param {number} strength the strength of the vortex
  85306. * @param {number} height the height of the vortex
  85307. */
  85308. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85309. if (!this._physicsEngine) {
  85310. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85311. return null;
  85312. }
  85313. if (this._physicsEngine.getImpostors().length === 0) {
  85314. return null;
  85315. }
  85316. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85317. event.dispose(false);
  85318. return event;
  85319. };
  85320. return PhysicsHelper;
  85321. }());
  85322. BABYLON.PhysicsHelper = PhysicsHelper;
  85323. /***** Radial explosion *****/
  85324. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85325. function PhysicsRadialExplosionEvent(scene) {
  85326. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85327. this._rays = [];
  85328. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85329. this._scene = scene;
  85330. }
  85331. /**
  85332. * Returns the data related to the radial explosion event (sphere & rays).
  85333. * @returns {PhysicsRadialExplosionEventData}
  85334. */
  85335. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85336. this._dataFetched = true;
  85337. return {
  85338. sphere: this._sphere,
  85339. rays: this._rays,
  85340. };
  85341. };
  85342. /**
  85343. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85344. * @param impostor
  85345. * @param {Vector3} origin the origin of the explosion
  85346. * @param {number} radius the explosion radius
  85347. * @param {number} strength the explosion strength
  85348. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85349. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85350. */
  85351. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85352. if (impostor.mass === 0) {
  85353. return null;
  85354. }
  85355. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85356. return null;
  85357. }
  85358. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85359. return null;
  85360. }
  85361. var impostorObjectCenter = impostor.getObjectCenter();
  85362. var direction = impostorObjectCenter.subtract(origin);
  85363. var ray = new BABYLON.Ray(origin, direction, radius);
  85364. this._rays.push(ray);
  85365. var hit = ray.intersectsMesh(impostor.object);
  85366. var contactPoint = hit.pickedPoint;
  85367. if (!contactPoint) {
  85368. return null;
  85369. }
  85370. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85371. if (distanceFromOrigin > radius) {
  85372. return null;
  85373. }
  85374. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85375. ? strength
  85376. : strength * (1 - (distanceFromOrigin / radius));
  85377. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85378. return { force: force, contactPoint: contactPoint };
  85379. };
  85380. /**
  85381. * Disposes the sphere.
  85382. * @param {bolean} force
  85383. */
  85384. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85385. var _this = this;
  85386. if (force === void 0) { force = true; }
  85387. if (force) {
  85388. this._sphere.dispose();
  85389. }
  85390. else {
  85391. setTimeout(function () {
  85392. if (!_this._dataFetched) {
  85393. _this._sphere.dispose();
  85394. }
  85395. }, 0);
  85396. }
  85397. };
  85398. /*** Helpers ***/
  85399. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85400. if (!this._sphere) {
  85401. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85402. this._sphere.isVisible = false;
  85403. }
  85404. };
  85405. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85406. var impostorObject = impostor.object;
  85407. this._prepareSphere();
  85408. this._sphere.position = origin;
  85409. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85410. this._sphere._updateBoundingInfo();
  85411. this._sphere.computeWorldMatrix(true);
  85412. return this._sphere.intersectsMesh(impostorObject, true);
  85413. };
  85414. return PhysicsRadialExplosionEvent;
  85415. }());
  85416. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85417. /***** Gravitational Field *****/
  85418. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85419. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85420. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85421. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85422. this._physicsHelper = physicsHelper;
  85423. this._scene = scene;
  85424. this._origin = origin;
  85425. this._radius = radius;
  85426. this._strength = strength;
  85427. this._falloff = falloff;
  85428. this._tickCallback = this._tick.bind(this);
  85429. }
  85430. /**
  85431. * Returns the data related to the gravitational field event (sphere).
  85432. * @returns {PhysicsGravitationalFieldEventData}
  85433. */
  85434. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85435. this._dataFetched = true;
  85436. return {
  85437. sphere: this._sphere,
  85438. };
  85439. };
  85440. /**
  85441. * Enables the gravitational field.
  85442. */
  85443. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85444. this._tickCallback.call(this);
  85445. this._scene.registerBeforeRender(this._tickCallback);
  85446. };
  85447. /**
  85448. * Disables the gravitational field.
  85449. */
  85450. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85451. this._scene.unregisterBeforeRender(this._tickCallback);
  85452. };
  85453. /**
  85454. * Disposes the sphere.
  85455. * @param {bolean} force
  85456. */
  85457. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85458. var _this = this;
  85459. if (force === void 0) { force = true; }
  85460. if (force) {
  85461. this._sphere.dispose();
  85462. }
  85463. else {
  85464. setTimeout(function () {
  85465. if (!_this._dataFetched) {
  85466. _this._sphere.dispose();
  85467. }
  85468. }, 0);
  85469. }
  85470. };
  85471. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85472. // Since the params won't change, we fetch the event only once
  85473. if (this._sphere) {
  85474. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85475. }
  85476. else {
  85477. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85478. if (radialExplosionEvent) {
  85479. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85480. }
  85481. }
  85482. };
  85483. return PhysicsGravitationalFieldEvent;
  85484. }());
  85485. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85486. /***** Updraft *****/
  85487. var PhysicsUpdraftEvent = /** @class */ (function () {
  85488. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85489. this._scene = _scene;
  85490. this._origin = _origin;
  85491. this._radius = _radius;
  85492. this._strength = _strength;
  85493. this._height = _height;
  85494. this._updraftMode = _updraftMode;
  85495. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85496. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85497. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85498. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85499. this._physicsEngine = this._scene.getPhysicsEngine();
  85500. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85501. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85502. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85503. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85504. }
  85505. this._tickCallback = this._tick.bind(this);
  85506. }
  85507. /**
  85508. * Returns the data related to the updraft event (cylinder).
  85509. * @returns {PhysicsUpdraftEventData}
  85510. */
  85511. PhysicsUpdraftEvent.prototype.getData = function () {
  85512. this._dataFetched = true;
  85513. return {
  85514. cylinder: this._cylinder,
  85515. };
  85516. };
  85517. /**
  85518. * Enables the updraft.
  85519. */
  85520. PhysicsUpdraftEvent.prototype.enable = function () {
  85521. this._tickCallback.call(this);
  85522. this._scene.registerBeforeRender(this._tickCallback);
  85523. };
  85524. /**
  85525. * Disables the cortex.
  85526. */
  85527. PhysicsUpdraftEvent.prototype.disable = function () {
  85528. this._scene.unregisterBeforeRender(this._tickCallback);
  85529. };
  85530. /**
  85531. * Disposes the sphere.
  85532. * @param {bolean} force
  85533. */
  85534. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85535. var _this = this;
  85536. if (force === void 0) { force = true; }
  85537. if (force) {
  85538. this._cylinder.dispose();
  85539. }
  85540. else {
  85541. setTimeout(function () {
  85542. if (!_this._dataFetched) {
  85543. _this._cylinder.dispose();
  85544. }
  85545. }, 0);
  85546. }
  85547. };
  85548. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85549. if (impostor.mass === 0) {
  85550. return null;
  85551. }
  85552. if (!this._intersectsWithCylinder(impostor)) {
  85553. return null;
  85554. }
  85555. var impostorObjectCenter = impostor.getObjectCenter();
  85556. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85557. var direction = this._originDirection;
  85558. }
  85559. else {
  85560. var direction = impostorObjectCenter.subtract(this._originTop);
  85561. }
  85562. var multiplier = this._strength * -1;
  85563. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85564. return { force: force, contactPoint: impostorObjectCenter };
  85565. };
  85566. PhysicsUpdraftEvent.prototype._tick = function () {
  85567. var _this = this;
  85568. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85569. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85570. if (!impostorForceAndContactPoint) {
  85571. return;
  85572. }
  85573. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85574. });
  85575. };
  85576. /*** Helpers ***/
  85577. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85578. if (!this._cylinder) {
  85579. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85580. height: this._height,
  85581. diameter: this._radius * 2,
  85582. }, this._scene);
  85583. this._cylinder.isVisible = false;
  85584. }
  85585. };
  85586. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85587. var impostorObject = impostor.object;
  85588. this._prepareCylinder();
  85589. this._cylinder.position = this._cylinderPosition;
  85590. return this._cylinder.intersectsMesh(impostorObject, true);
  85591. };
  85592. return PhysicsUpdraftEvent;
  85593. }());
  85594. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85595. /***** Vortex *****/
  85596. var PhysicsVortexEvent = /** @class */ (function () {
  85597. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85598. this._scene = _scene;
  85599. this._origin = _origin;
  85600. this._radius = _radius;
  85601. this._strength = _strength;
  85602. this._height = _height;
  85603. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85604. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85605. this._updraftMultiplier = 0.02;
  85606. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85607. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85608. this._physicsEngine = this._scene.getPhysicsEngine();
  85609. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85610. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85611. this._tickCallback = this._tick.bind(this);
  85612. }
  85613. /**
  85614. * Returns the data related to the vortex event (cylinder).
  85615. * @returns {PhysicsVortexEventData}
  85616. */
  85617. PhysicsVortexEvent.prototype.getData = function () {
  85618. this._dataFetched = true;
  85619. return {
  85620. cylinder: this._cylinder,
  85621. };
  85622. };
  85623. /**
  85624. * Enables the vortex.
  85625. */
  85626. PhysicsVortexEvent.prototype.enable = function () {
  85627. this._tickCallback.call(this);
  85628. this._scene.registerBeforeRender(this._tickCallback);
  85629. };
  85630. /**
  85631. * Disables the cortex.
  85632. */
  85633. PhysicsVortexEvent.prototype.disable = function () {
  85634. this._scene.unregisterBeforeRender(this._tickCallback);
  85635. };
  85636. /**
  85637. * Disposes the sphere.
  85638. * @param {bolean} force
  85639. */
  85640. PhysicsVortexEvent.prototype.dispose = function (force) {
  85641. var _this = this;
  85642. if (force === void 0) { force = true; }
  85643. if (force) {
  85644. this._cylinder.dispose();
  85645. }
  85646. else {
  85647. setTimeout(function () {
  85648. if (!_this._dataFetched) {
  85649. _this._cylinder.dispose();
  85650. }
  85651. }, 0);
  85652. }
  85653. };
  85654. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85655. if (impostor.mass === 0) {
  85656. return null;
  85657. }
  85658. if (!this._intersectsWithCylinder(impostor)) {
  85659. return null;
  85660. }
  85661. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85662. return null;
  85663. }
  85664. var impostorObjectCenter = impostor.getObjectCenter();
  85665. 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)
  85666. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85667. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85668. var hit = ray.intersectsMesh(impostor.object);
  85669. var contactPoint = hit.pickedPoint;
  85670. if (!contactPoint) {
  85671. return null;
  85672. }
  85673. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85674. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85675. var directionToOrigin = contactPoint.normalize();
  85676. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85677. directionToOrigin = directionToOrigin.negate();
  85678. }
  85679. // TODO: find a more physically based solution
  85680. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85681. var forceX = directionToOrigin.x * this._strength / 8;
  85682. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85683. var forceZ = directionToOrigin.z * this._strength / 8;
  85684. }
  85685. else {
  85686. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85687. var forceY = this._originTop.y * this._updraftMultiplier;
  85688. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85689. }
  85690. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85691. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85692. return { force: force, contactPoint: impostorObjectCenter };
  85693. };
  85694. PhysicsVortexEvent.prototype._tick = function () {
  85695. var _this = this;
  85696. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85697. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85698. if (!impostorForceAndContactPoint) {
  85699. return;
  85700. }
  85701. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85702. });
  85703. };
  85704. /*** Helpers ***/
  85705. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85706. if (!this._cylinder) {
  85707. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85708. height: this._height,
  85709. diameter: this._radius * 2,
  85710. }, this._scene);
  85711. this._cylinder.isVisible = false;
  85712. }
  85713. };
  85714. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85715. var impostorObject = impostor.object;
  85716. this._prepareCylinder();
  85717. this._cylinder.position = this._cylinderPosition;
  85718. return this._cylinder.intersectsMesh(impostorObject, true);
  85719. };
  85720. return PhysicsVortexEvent;
  85721. }());
  85722. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85723. /***** Enums *****/
  85724. /**
  85725. * The strenght of the force in correspondence to the distance of the affected object
  85726. */
  85727. var PhysicsRadialImpulseFalloff;
  85728. (function (PhysicsRadialImpulseFalloff) {
  85729. /** Defines that impulse is constant in strength across it's whole radius */
  85730. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85731. /** DEfines that impulse gets weaker if it's further from the origin */
  85732. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85733. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85734. /**
  85735. * The strenght of the force in correspondence to the distance of the affected object
  85736. */
  85737. var PhysicsUpdraftMode;
  85738. (function (PhysicsUpdraftMode) {
  85739. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85740. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85741. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85742. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85743. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85744. })(BABYLON || (BABYLON = {}));
  85745. //# sourceMappingURL=babylon.physicsHelper.js.map
  85746. var BABYLON;
  85747. (function (BABYLON) {
  85748. var CannonJSPlugin = /** @class */ (function () {
  85749. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85750. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85751. if (iterations === void 0) { iterations = 10; }
  85752. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85753. this.name = "CannonJSPlugin";
  85754. this._physicsMaterials = new Array();
  85755. this._fixedTimeStep = 1 / 60;
  85756. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85757. this.BJSCANNON = CANNON;
  85758. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85759. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85760. this._tmpPosition = BABYLON.Vector3.Zero();
  85761. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85762. this._tmpUnityRotation = new BABYLON.Quaternion();
  85763. if (!this.isSupported()) {
  85764. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85765. return;
  85766. }
  85767. this._extendNamespace();
  85768. this.world = new this.BJSCANNON.World();
  85769. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85770. this.world.solver.iterations = iterations;
  85771. }
  85772. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85773. this.world.gravity.copy(gravity);
  85774. };
  85775. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85776. this._fixedTimeStep = timeStep;
  85777. };
  85778. CannonJSPlugin.prototype.getTimeStep = function () {
  85779. return this._fixedTimeStep;
  85780. };
  85781. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85782. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85783. };
  85784. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85785. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85786. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85787. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85788. };
  85789. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85790. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85791. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85792. impostor.physicsBody.applyForce(impulse, worldPoint);
  85793. };
  85794. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85795. //parent-child relationship. Does this impostor has a parent impostor?
  85796. if (impostor.parent) {
  85797. if (impostor.physicsBody) {
  85798. this.removePhysicsBody(impostor);
  85799. //TODO is that needed?
  85800. impostor.forceUpdate();
  85801. }
  85802. return;
  85803. }
  85804. //should a new body be created for this impostor?
  85805. if (impostor.isBodyInitRequired()) {
  85806. var shape = this._createShape(impostor);
  85807. //unregister events, if body is being changed
  85808. var oldBody = impostor.physicsBody;
  85809. if (oldBody) {
  85810. this.removePhysicsBody(impostor);
  85811. }
  85812. //create the body and material
  85813. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85814. var bodyCreationObject = {
  85815. mass: impostor.getParam("mass"),
  85816. material: material
  85817. };
  85818. // A simple extend, in case native options were used.
  85819. var nativeOptions = impostor.getParam("nativeOptions");
  85820. for (var key in nativeOptions) {
  85821. if (nativeOptions.hasOwnProperty(key)) {
  85822. bodyCreationObject[key] = nativeOptions[key];
  85823. }
  85824. }
  85825. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85826. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85827. this.world.addEventListener("preStep", impostor.beforeStep);
  85828. this.world.addEventListener("postStep", impostor.afterStep);
  85829. impostor.physicsBody.addShape(shape);
  85830. this.world.add(impostor.physicsBody);
  85831. //try to keep the body moving in the right direction by taking old properties.
  85832. //Should be tested!
  85833. if (oldBody) {
  85834. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85835. impostor.physicsBody[param].copy(oldBody[param]);
  85836. });
  85837. }
  85838. this._processChildMeshes(impostor);
  85839. }
  85840. //now update the body's transformation
  85841. this._updatePhysicsBodyTransformation(impostor);
  85842. };
  85843. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85844. var _this = this;
  85845. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85846. var currentRotation = mainImpostor.object.rotationQuaternion;
  85847. if (meshChildren.length) {
  85848. var processMesh = function (localPosition, mesh) {
  85849. if (!currentRotation || !mesh.rotationQuaternion) {
  85850. return;
  85851. }
  85852. var childImpostor = mesh.getPhysicsImpostor();
  85853. if (childImpostor) {
  85854. var parent = childImpostor.parent;
  85855. if (parent !== mainImpostor) {
  85856. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85857. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85858. if (childImpostor.physicsBody) {
  85859. _this.removePhysicsBody(childImpostor);
  85860. childImpostor.physicsBody = null;
  85861. }
  85862. childImpostor.parent = mainImpostor;
  85863. childImpostor.resetUpdateFlags();
  85864. 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));
  85865. //Add the mass of the children.
  85866. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85867. }
  85868. }
  85869. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85870. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85871. };
  85872. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85873. }
  85874. };
  85875. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85876. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85877. this.world.removeEventListener("preStep", impostor.beforeStep);
  85878. this.world.removeEventListener("postStep", impostor.afterStep);
  85879. this.world.remove(impostor.physicsBody);
  85880. };
  85881. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85882. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85883. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85884. if (!mainBody || !connectedBody) {
  85885. return;
  85886. }
  85887. var constraint;
  85888. var jointData = impostorJoint.joint.jointData;
  85889. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85890. var constraintData = {
  85891. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85892. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85893. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85894. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85895. maxForce: jointData.nativeParams.maxForce,
  85896. collideConnected: !!jointData.collision
  85897. };
  85898. switch (impostorJoint.joint.type) {
  85899. case BABYLON.PhysicsJoint.HingeJoint:
  85900. case BABYLON.PhysicsJoint.Hinge2Joint:
  85901. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85902. break;
  85903. case BABYLON.PhysicsJoint.DistanceJoint:
  85904. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85905. break;
  85906. case BABYLON.PhysicsJoint.SpringJoint:
  85907. var springData = jointData;
  85908. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85909. restLength: springData.length,
  85910. stiffness: springData.stiffness,
  85911. damping: springData.damping,
  85912. localAnchorA: constraintData.pivotA,
  85913. localAnchorB: constraintData.pivotB
  85914. });
  85915. break;
  85916. case BABYLON.PhysicsJoint.LockJoint:
  85917. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  85918. break;
  85919. case BABYLON.PhysicsJoint.PointToPointJoint:
  85920. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85921. default:
  85922. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  85923. break;
  85924. }
  85925. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  85926. constraint.collideConnected = !!jointData.collision;
  85927. impostorJoint.joint.physicsJoint = constraint;
  85928. //don't add spring as constraint, as it is not one.
  85929. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  85930. this.world.addConstraint(constraint);
  85931. }
  85932. else {
  85933. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  85934. constraint.applyForce();
  85935. });
  85936. }
  85937. };
  85938. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85939. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85940. };
  85941. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  85942. var index;
  85943. var mat;
  85944. for (index = 0; index < this._physicsMaterials.length; index++) {
  85945. mat = this._physicsMaterials[index];
  85946. if (mat.friction === friction && mat.restitution === restitution) {
  85947. return mat;
  85948. }
  85949. }
  85950. var currentMat = new this.BJSCANNON.Material(name);
  85951. currentMat.friction = friction;
  85952. currentMat.restitution = restitution;
  85953. this._physicsMaterials.push(currentMat);
  85954. return currentMat;
  85955. };
  85956. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  85957. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  85958. };
  85959. CannonJSPlugin.prototype._createShape = function (impostor) {
  85960. var object = impostor.object;
  85961. var returnValue;
  85962. var extendSize = impostor.getObjectExtendSize();
  85963. switch (impostor.type) {
  85964. case BABYLON.PhysicsImpostor.SphereImpostor:
  85965. var radiusX = extendSize.x;
  85966. var radiusY = extendSize.y;
  85967. var radiusZ = extendSize.z;
  85968. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  85969. break;
  85970. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  85971. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85972. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  85973. break;
  85974. case BABYLON.PhysicsImpostor.BoxImpostor:
  85975. var box = extendSize.scale(0.5);
  85976. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  85977. break;
  85978. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85979. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  85980. returnValue = new this.BJSCANNON.Plane();
  85981. break;
  85982. case BABYLON.PhysicsImpostor.MeshImpostor:
  85983. // should transform the vertex data to world coordinates!!
  85984. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  85985. var rawFaces = object.getIndices ? object.getIndices() : [];
  85986. if (!rawVerts)
  85987. return;
  85988. // get only scale! so the object could transform correctly.
  85989. var oldPosition = object.position.clone();
  85990. var oldRotation = object.rotation && object.rotation.clone();
  85991. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  85992. object.position.copyFromFloats(0, 0, 0);
  85993. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85994. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85995. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85996. var transform = object.computeWorldMatrix(true);
  85997. // convert rawVerts to object space
  85998. var temp = new Array();
  85999. var index;
  86000. for (index = 0; index < rawVerts.length; index += 3) {
  86001. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  86002. }
  86003. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  86004. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  86005. //now set back the transformation!
  86006. object.position.copyFrom(oldPosition);
  86007. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  86008. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  86009. break;
  86010. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  86011. var oldPosition2 = object.position.clone();
  86012. var oldRotation2 = object.rotation && object.rotation.clone();
  86013. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  86014. object.position.copyFromFloats(0, 0, 0);
  86015. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  86016. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  86017. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  86018. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  86019. returnValue = this._createHeightmap(object);
  86020. object.position.copyFrom(oldPosition2);
  86021. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  86022. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  86023. object.computeWorldMatrix(true);
  86024. break;
  86025. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86026. returnValue = new this.BJSCANNON.Particle();
  86027. break;
  86028. }
  86029. return returnValue;
  86030. };
  86031. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  86032. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  86033. var transform = object.computeWorldMatrix(true);
  86034. // convert rawVerts to object space
  86035. var temp = new Array();
  86036. var index;
  86037. for (index = 0; index < pos.length; index += 3) {
  86038. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  86039. }
  86040. pos = temp;
  86041. var matrix = new Array();
  86042. //For now pointDepth will not be used and will be automatically calculated.
  86043. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  86044. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  86045. var boundingInfo = object.getBoundingInfo();
  86046. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  86047. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  86048. var elementSize = dim * 2 / arraySize;
  86049. for (var i = 0; i < pos.length; i = i + 3) {
  86050. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  86051. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  86052. var y = -pos[i + 2] + minY;
  86053. if (!matrix[x]) {
  86054. matrix[x] = [];
  86055. }
  86056. if (!matrix[x][z]) {
  86057. matrix[x][z] = y;
  86058. }
  86059. matrix[x][z] = Math.max(y, matrix[x][z]);
  86060. }
  86061. for (var x = 0; x <= arraySize; ++x) {
  86062. if (!matrix[x]) {
  86063. var loc = 1;
  86064. while (!matrix[(x + loc) % arraySize]) {
  86065. loc++;
  86066. }
  86067. matrix[x] = matrix[(x + loc) % arraySize].slice();
  86068. //console.log("missing x", x);
  86069. }
  86070. for (var z = 0; z <= arraySize; ++z) {
  86071. if (!matrix[x][z]) {
  86072. var loc = 1;
  86073. var newValue;
  86074. while (newValue === undefined) {
  86075. newValue = matrix[x][(z + loc++) % arraySize];
  86076. }
  86077. matrix[x][z] = newValue;
  86078. }
  86079. }
  86080. }
  86081. var shape = new this.BJSCANNON.Heightfield(matrix, {
  86082. elementSize: elementSize
  86083. });
  86084. //For future reference, needed for body transformation
  86085. shape.minY = minY;
  86086. return shape;
  86087. };
  86088. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  86089. var object = impostor.object;
  86090. //make sure it is updated...
  86091. object.computeWorldMatrix && object.computeWorldMatrix(true);
  86092. // The delta between the mesh position and the mesh bounding box center
  86093. var bInfo = object.getBoundingInfo();
  86094. if (!bInfo)
  86095. return;
  86096. var center = impostor.getObjectCenter();
  86097. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  86098. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  86099. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  86100. this._tmpPosition.copyFrom(center);
  86101. var quaternion = object.rotationQuaternion;
  86102. if (!quaternion) {
  86103. return;
  86104. }
  86105. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  86106. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  86107. //-90 DEG in X, precalculated
  86108. quaternion = quaternion.multiply(this._minus90X);
  86109. //Invert! (Precalculated, 90 deg in X)
  86110. //No need to clone. this will never change.
  86111. impostor.setDeltaRotation(this._plus90X);
  86112. }
  86113. //If it is a heightfield, if should be centered.
  86114. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86115. var mesh = object;
  86116. var boundingInfo = mesh.getBoundingInfo();
  86117. //calculate the correct body position:
  86118. var rotationQuaternion = mesh.rotationQuaternion;
  86119. mesh.rotationQuaternion = this._tmpUnityRotation;
  86120. mesh.computeWorldMatrix(true);
  86121. //get original center with no rotation
  86122. var c = center.clone();
  86123. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86124. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86125. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86126. mesh.setPreTransformMatrix(p);
  86127. mesh.computeWorldMatrix(true);
  86128. //calculate the translation
  86129. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86130. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86131. //add it inverted to the delta
  86132. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86133. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86134. //rotation is back
  86135. mesh.rotationQuaternion = rotationQuaternion;
  86136. mesh.setPreTransformMatrix(oldPivot);
  86137. mesh.computeWorldMatrix(true);
  86138. }
  86139. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86140. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86141. //this._tmpPosition.copyFrom(object.position);
  86142. }
  86143. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86144. //Now update the impostor object
  86145. impostor.physicsBody.position.copy(this._tmpPosition);
  86146. impostor.physicsBody.quaternion.copy(quaternion);
  86147. };
  86148. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86149. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86150. if (impostor.object.rotationQuaternion) {
  86151. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86152. }
  86153. };
  86154. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86155. impostor.physicsBody.position.copy(newPosition);
  86156. impostor.physicsBody.quaternion.copy(newRotation);
  86157. };
  86158. CannonJSPlugin.prototype.isSupported = function () {
  86159. return this.BJSCANNON !== undefined;
  86160. };
  86161. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86162. impostor.physicsBody.velocity.copy(velocity);
  86163. };
  86164. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86165. impostor.physicsBody.angularVelocity.copy(velocity);
  86166. };
  86167. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86168. var v = impostor.physicsBody.velocity;
  86169. if (!v) {
  86170. return null;
  86171. }
  86172. return new BABYLON.Vector3(v.x, v.y, v.z);
  86173. };
  86174. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86175. var v = impostor.physicsBody.angularVelocity;
  86176. if (!v) {
  86177. return null;
  86178. }
  86179. return new BABYLON.Vector3(v.x, v.y, v.z);
  86180. };
  86181. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86182. impostor.physicsBody.mass = mass;
  86183. impostor.physicsBody.updateMassProperties();
  86184. };
  86185. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86186. return impostor.physicsBody.mass;
  86187. };
  86188. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86189. return impostor.physicsBody.material.friction;
  86190. };
  86191. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86192. impostor.physicsBody.material.friction = friction;
  86193. };
  86194. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86195. return impostor.physicsBody.material.restitution;
  86196. };
  86197. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86198. impostor.physicsBody.material.restitution = restitution;
  86199. };
  86200. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86201. impostor.physicsBody.sleep();
  86202. };
  86203. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86204. impostor.physicsBody.wakeUp();
  86205. };
  86206. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86207. joint.physicsJoint.distance = maxDistance;
  86208. };
  86209. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86210. // if (!motorIndex) {
  86211. // joint.physicsJoint.enableMotor();
  86212. // }
  86213. // }
  86214. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86215. // if (!motorIndex) {
  86216. // joint.physicsJoint.disableMotor();
  86217. // }
  86218. // }
  86219. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86220. if (!motorIndex) {
  86221. joint.physicsJoint.enableMotor();
  86222. joint.physicsJoint.setMotorSpeed(speed);
  86223. if (maxForce) {
  86224. this.setLimit(joint, maxForce);
  86225. }
  86226. }
  86227. };
  86228. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86229. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86230. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86231. };
  86232. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86233. var body = impostor.physicsBody;
  86234. mesh.position.x = body.position.x;
  86235. mesh.position.y = body.position.y;
  86236. mesh.position.z = body.position.z;
  86237. if (mesh.rotationQuaternion) {
  86238. mesh.rotationQuaternion.x = body.quaternion.x;
  86239. mesh.rotationQuaternion.y = body.quaternion.y;
  86240. mesh.rotationQuaternion.z = body.quaternion.z;
  86241. mesh.rotationQuaternion.w = body.quaternion.w;
  86242. }
  86243. };
  86244. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86245. var shape = impostor.physicsBody.shapes[0];
  86246. return shape.boundingSphereRadius;
  86247. };
  86248. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86249. var shape = impostor.physicsBody.shapes[0];
  86250. result.x = shape.halfExtents.x * 2;
  86251. result.y = shape.halfExtents.y * 2;
  86252. result.z = shape.halfExtents.z * 2;
  86253. };
  86254. CannonJSPlugin.prototype.dispose = function () {
  86255. };
  86256. CannonJSPlugin.prototype._extendNamespace = function () {
  86257. //this will force cannon to execute at least one step when using interpolation
  86258. var step_tmp1 = new this.BJSCANNON.Vec3();
  86259. var Engine = this.BJSCANNON;
  86260. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86261. maxSubSteps = maxSubSteps || 10;
  86262. timeSinceLastCalled = timeSinceLastCalled || 0;
  86263. if (timeSinceLastCalled === 0) {
  86264. this.internalStep(dt);
  86265. this.time += dt;
  86266. }
  86267. else {
  86268. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86269. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86270. var t0 = performance.now();
  86271. for (var i = 0; i !== internalSteps; i++) {
  86272. this.internalStep(dt);
  86273. if (performance.now() - t0 > dt * 1000) {
  86274. break;
  86275. }
  86276. }
  86277. this.time += timeSinceLastCalled;
  86278. var h = this.time % dt;
  86279. var h_div_dt = h / dt;
  86280. var interpvelo = step_tmp1;
  86281. var bodies = this.bodies;
  86282. for (var j = 0; j !== bodies.length; j++) {
  86283. var b = bodies[j];
  86284. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86285. b.position.vsub(b.previousPosition, interpvelo);
  86286. interpvelo.scale(h_div_dt, interpvelo);
  86287. b.position.vadd(interpvelo, b.interpolatedPosition);
  86288. }
  86289. else {
  86290. b.interpolatedPosition.copy(b.position);
  86291. b.interpolatedQuaternion.copy(b.quaternion);
  86292. }
  86293. }
  86294. }
  86295. };
  86296. };
  86297. return CannonJSPlugin;
  86298. }());
  86299. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86300. })(BABYLON || (BABYLON = {}));
  86301. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86302. var BABYLON;
  86303. (function (BABYLON) {
  86304. var OimoJSPlugin = /** @class */ (function () {
  86305. function OimoJSPlugin(iterations) {
  86306. this.name = "OimoJSPlugin";
  86307. this._tmpImpostorsArray = [];
  86308. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86309. this.BJSOIMO = OIMO;
  86310. this.world = new this.BJSOIMO.World({
  86311. iterations: iterations
  86312. });
  86313. this.world.clear();
  86314. }
  86315. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86316. this.world.gravity.copy(gravity);
  86317. };
  86318. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86319. this.world.timeStep = timeStep;
  86320. };
  86321. OimoJSPlugin.prototype.getTimeStep = function () {
  86322. return this.world.timeStep;
  86323. };
  86324. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86325. var _this = this;
  86326. impostors.forEach(function (impostor) {
  86327. impostor.beforeStep();
  86328. });
  86329. this.world.step();
  86330. impostors.forEach(function (impostor) {
  86331. impostor.afterStep();
  86332. //update the ordered impostors array
  86333. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86334. });
  86335. //check for collisions
  86336. var contact = this.world.contacts;
  86337. while (contact !== null) {
  86338. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86339. contact = contact.next;
  86340. continue;
  86341. }
  86342. //is this body colliding with any other? get the impostor
  86343. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86344. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86345. if (!mainImpostor || !collidingImpostor) {
  86346. contact = contact.next;
  86347. continue;
  86348. }
  86349. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86350. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86351. contact = contact.next;
  86352. }
  86353. };
  86354. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86355. var mass = impostor.physicsBody.mass;
  86356. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86357. };
  86358. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86359. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86360. this.applyImpulse(impostor, force, contactPoint);
  86361. };
  86362. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86363. var _this = this;
  86364. //parent-child relationship. Does this impostor has a parent impostor?
  86365. if (impostor.parent) {
  86366. if (impostor.physicsBody) {
  86367. this.removePhysicsBody(impostor);
  86368. //TODO is that needed?
  86369. impostor.forceUpdate();
  86370. }
  86371. return;
  86372. }
  86373. if (impostor.isBodyInitRequired()) {
  86374. var bodyConfig = {
  86375. name: impostor.uniqueId,
  86376. //Oimo must have mass, also for static objects.
  86377. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86378. size: [],
  86379. type: [],
  86380. pos: [],
  86381. posShape: [],
  86382. rot: [],
  86383. rotShape: [],
  86384. move: impostor.getParam("mass") !== 0,
  86385. density: impostor.getParam("mass"),
  86386. friction: impostor.getParam("friction"),
  86387. restitution: impostor.getParam("restitution"),
  86388. //Supporting older versions of Oimo
  86389. world: this.world
  86390. };
  86391. var impostors = [impostor];
  86392. var addToArray = function (parent) {
  86393. if (!parent.getChildMeshes)
  86394. return;
  86395. parent.getChildMeshes().forEach(function (m) {
  86396. if (m.physicsImpostor) {
  86397. impostors.push(m.physicsImpostor);
  86398. //m.physicsImpostor._init();
  86399. }
  86400. });
  86401. };
  86402. addToArray(impostor.object);
  86403. var checkWithEpsilon_1 = function (value) {
  86404. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86405. };
  86406. impostors.forEach(function (i) {
  86407. if (!i.object.rotationQuaternion) {
  86408. return;
  86409. }
  86410. //get the correct bounding box
  86411. var oldQuaternion = i.object.rotationQuaternion;
  86412. var rot = oldQuaternion.toEulerAngles();
  86413. var extendSize = i.getObjectExtendSize();
  86414. var radToDeg = 57.295779513082320876;
  86415. if (i === impostor) {
  86416. var center = impostor.getObjectCenter();
  86417. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86418. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86419. //Can also use Array.prototype.push.apply
  86420. bodyConfig.pos.push(center.x);
  86421. bodyConfig.pos.push(center.y);
  86422. bodyConfig.pos.push(center.z);
  86423. bodyConfig.posShape.push(0, 0, 0);
  86424. //tmp solution
  86425. bodyConfig.rot.push(rot.x * radToDeg);
  86426. bodyConfig.rot.push(rot.y * radToDeg);
  86427. bodyConfig.rot.push(rot.z * radToDeg);
  86428. bodyConfig.rotShape.push(0, 0, 0);
  86429. }
  86430. else {
  86431. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86432. bodyConfig.posShape.push(localPosition.x);
  86433. bodyConfig.posShape.push(localPosition.y);
  86434. bodyConfig.posShape.push(localPosition.z);
  86435. bodyConfig.pos.push(0, 0, 0);
  86436. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86437. bodyConfig.rot.push(0);
  86438. bodyConfig.rot.push(0);
  86439. bodyConfig.rot.push(0);
  86440. bodyConfig.rotShape.push(rot.x * radToDeg);
  86441. bodyConfig.rotShape.push(rot.y * radToDeg);
  86442. bodyConfig.rotShape.push(rot.z * radToDeg);
  86443. }
  86444. // register mesh
  86445. switch (i.type) {
  86446. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86447. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86448. case BABYLON.PhysicsImpostor.SphereImpostor:
  86449. var radiusX = extendSize.x;
  86450. var radiusY = extendSize.y;
  86451. var radiusZ = extendSize.z;
  86452. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86453. bodyConfig.type.push('sphere');
  86454. //due to the way oimo works with compounds, add 3 times
  86455. bodyConfig.size.push(size);
  86456. bodyConfig.size.push(size);
  86457. bodyConfig.size.push(size);
  86458. break;
  86459. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86460. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86461. var sizeY = checkWithEpsilon_1(extendSize.y);
  86462. bodyConfig.type.push('cylinder');
  86463. bodyConfig.size.push(sizeX);
  86464. bodyConfig.size.push(sizeY);
  86465. //due to the way oimo works with compounds, add one more value.
  86466. bodyConfig.size.push(sizeY);
  86467. break;
  86468. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86469. case BABYLON.PhysicsImpostor.BoxImpostor:
  86470. default:
  86471. var sizeX = checkWithEpsilon_1(extendSize.x);
  86472. var sizeY = checkWithEpsilon_1(extendSize.y);
  86473. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86474. bodyConfig.type.push('box');
  86475. //if (i === impostor) {
  86476. bodyConfig.size.push(sizeX);
  86477. bodyConfig.size.push(sizeY);
  86478. bodyConfig.size.push(sizeZ);
  86479. //} else {
  86480. // bodyConfig.size.push(0,0,0);
  86481. //}
  86482. break;
  86483. }
  86484. //actually not needed, but hey...
  86485. i.object.rotationQuaternion = oldQuaternion;
  86486. });
  86487. impostor.physicsBody = this.world.add(bodyConfig);
  86488. }
  86489. else {
  86490. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86491. }
  86492. impostor.setDeltaPosition(this._tmpPositionVector);
  86493. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86494. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86495. };
  86496. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86497. //impostor.physicsBody.dispose();
  86498. //Same as : (older oimo versions)
  86499. this.world.removeRigidBody(impostor.physicsBody);
  86500. };
  86501. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86502. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86503. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86504. if (!mainBody || !connectedBody) {
  86505. return;
  86506. }
  86507. var jointData = impostorJoint.joint.jointData;
  86508. var options = jointData.nativeParams || {};
  86509. var type;
  86510. var nativeJointData = {
  86511. body1: mainBody,
  86512. body2: connectedBody,
  86513. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86514. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86515. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86516. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86517. min: options.min,
  86518. max: options.max,
  86519. collision: options.collision || jointData.collision,
  86520. spring: options.spring,
  86521. //supporting older version of Oimo
  86522. world: this.world
  86523. };
  86524. switch (impostorJoint.joint.type) {
  86525. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86526. type = "jointBall";
  86527. break;
  86528. case BABYLON.PhysicsJoint.SpringJoint:
  86529. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86530. var springData = jointData;
  86531. nativeJointData.min = springData.length || nativeJointData.min;
  86532. //Max should also be set, just make sure it is at least min
  86533. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86534. case BABYLON.PhysicsJoint.DistanceJoint:
  86535. type = "jointDistance";
  86536. nativeJointData.max = jointData.maxDistance;
  86537. break;
  86538. case BABYLON.PhysicsJoint.PrismaticJoint:
  86539. type = "jointPrisme";
  86540. break;
  86541. case BABYLON.PhysicsJoint.SliderJoint:
  86542. type = "jointSlide";
  86543. break;
  86544. case BABYLON.PhysicsJoint.WheelJoint:
  86545. type = "jointWheel";
  86546. break;
  86547. case BABYLON.PhysicsJoint.HingeJoint:
  86548. default:
  86549. type = "jointHinge";
  86550. break;
  86551. }
  86552. nativeJointData.type = type;
  86553. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86554. };
  86555. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86556. //Bug in Oimo prevents us from disposing a joint in the playground
  86557. //joint.joint.physicsJoint.dispose();
  86558. //So we will bruteforce it!
  86559. try {
  86560. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86561. }
  86562. catch (e) {
  86563. BABYLON.Tools.Warn(e);
  86564. }
  86565. };
  86566. OimoJSPlugin.prototype.isSupported = function () {
  86567. return this.BJSOIMO !== undefined;
  86568. };
  86569. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86570. if (!impostor.physicsBody.sleeping) {
  86571. //TODO check that
  86572. /*if (impostor.physicsBody.shapes.next) {
  86573. var parentShape = this._getLastShape(impostor.physicsBody);
  86574. impostor.object.position.copyFrom(parentShape.position);
  86575. console.log(parentShape.position);
  86576. } else {*/
  86577. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86578. //}
  86579. if (impostor.object.rotationQuaternion) {
  86580. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86581. }
  86582. }
  86583. };
  86584. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86585. var body = impostor.physicsBody;
  86586. body.position.copy(newPosition);
  86587. body.orientation.copy(newRotation);
  86588. body.syncShapes();
  86589. body.awake();
  86590. };
  86591. /*private _getLastShape(body: any): any {
  86592. var lastShape = body.shapes;
  86593. while (lastShape.next) {
  86594. lastShape = lastShape.next;
  86595. }
  86596. return lastShape;
  86597. }*/
  86598. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86599. impostor.physicsBody.linearVelocity.copy(velocity);
  86600. };
  86601. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86602. impostor.physicsBody.angularVelocity.copy(velocity);
  86603. };
  86604. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86605. var v = impostor.physicsBody.linearVelocity;
  86606. if (!v) {
  86607. return null;
  86608. }
  86609. return new BABYLON.Vector3(v.x, v.y, v.z);
  86610. };
  86611. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86612. var v = impostor.physicsBody.angularVelocity;
  86613. if (!v) {
  86614. return null;
  86615. }
  86616. return new BABYLON.Vector3(v.x, v.y, v.z);
  86617. };
  86618. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86619. var staticBody = mass === 0;
  86620. //this will actually set the body's density and not its mass.
  86621. //But this is how oimo treats the mass variable.
  86622. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86623. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86624. };
  86625. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86626. return impostor.physicsBody.shapes.density;
  86627. };
  86628. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86629. return impostor.physicsBody.shapes.friction;
  86630. };
  86631. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86632. impostor.physicsBody.shapes.friction = friction;
  86633. };
  86634. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86635. return impostor.physicsBody.shapes.restitution;
  86636. };
  86637. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86638. impostor.physicsBody.shapes.restitution = restitution;
  86639. };
  86640. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86641. impostor.physicsBody.sleep();
  86642. };
  86643. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86644. impostor.physicsBody.awake();
  86645. };
  86646. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86647. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86648. if (minDistance !== void 0) {
  86649. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86650. }
  86651. };
  86652. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86653. //TODO separate rotational and transational motors.
  86654. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86655. if (motor) {
  86656. motor.setMotor(speed, maxForce);
  86657. }
  86658. };
  86659. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86660. //TODO separate rotational and transational motors.
  86661. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86662. if (motor) {
  86663. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86664. }
  86665. };
  86666. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86667. var body = impostor.physicsBody;
  86668. mesh.position.x = body.position.x;
  86669. mesh.position.y = body.position.y;
  86670. mesh.position.z = body.position.z;
  86671. if (mesh.rotationQuaternion) {
  86672. mesh.rotationQuaternion.x = body.orientation.x;
  86673. mesh.rotationQuaternion.y = body.orientation.y;
  86674. mesh.rotationQuaternion.z = body.orientation.z;
  86675. mesh.rotationQuaternion.w = body.orientation.s;
  86676. }
  86677. };
  86678. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86679. return impostor.physicsBody.shapes.radius;
  86680. };
  86681. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86682. var shape = impostor.physicsBody.shapes;
  86683. result.x = shape.halfWidth * 2;
  86684. result.y = shape.halfHeight * 2;
  86685. result.z = shape.halfDepth * 2;
  86686. };
  86687. OimoJSPlugin.prototype.dispose = function () {
  86688. this.world.clear();
  86689. };
  86690. return OimoJSPlugin;
  86691. }());
  86692. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86693. })(BABYLON || (BABYLON = {}));
  86694. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86695. var BABYLON;
  86696. (function (BABYLON) {
  86697. /*
  86698. * Based on jsTGALoader - Javascript loader for TGA file
  86699. * By Vincent Thibault
  86700. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86701. */
  86702. var TGATools = /** @class */ (function () {
  86703. function TGATools() {
  86704. }
  86705. TGATools.GetTGAHeader = function (data) {
  86706. var offset = 0;
  86707. var header = {
  86708. id_length: data[offset++],
  86709. colormap_type: data[offset++],
  86710. image_type: data[offset++],
  86711. colormap_index: data[offset++] | data[offset++] << 8,
  86712. colormap_length: data[offset++] | data[offset++] << 8,
  86713. colormap_size: data[offset++],
  86714. origin: [
  86715. data[offset++] | data[offset++] << 8,
  86716. data[offset++] | data[offset++] << 8
  86717. ],
  86718. width: data[offset++] | data[offset++] << 8,
  86719. height: data[offset++] | data[offset++] << 8,
  86720. pixel_size: data[offset++],
  86721. flags: data[offset++]
  86722. };
  86723. return header;
  86724. };
  86725. TGATools.UploadContent = function (gl, data) {
  86726. // Not enough data to contain header ?
  86727. if (data.length < 19) {
  86728. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86729. return;
  86730. }
  86731. // Read Header
  86732. var offset = 18;
  86733. var header = TGATools.GetTGAHeader(data);
  86734. // Assume it's a valid Targa file.
  86735. if (header.id_length + offset > data.length) {
  86736. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86737. return;
  86738. }
  86739. // Skip not needed data
  86740. offset += header.id_length;
  86741. var use_rle = false;
  86742. var use_pal = false;
  86743. var use_grey = false;
  86744. // Get some informations.
  86745. switch (header.image_type) {
  86746. case TGATools._TYPE_RLE_INDEXED:
  86747. use_rle = true;
  86748. case TGATools._TYPE_INDEXED:
  86749. use_pal = true;
  86750. break;
  86751. case TGATools._TYPE_RLE_RGB:
  86752. use_rle = true;
  86753. case TGATools._TYPE_RGB:
  86754. // use_rgb = true;
  86755. break;
  86756. case TGATools._TYPE_RLE_GREY:
  86757. use_rle = true;
  86758. case TGATools._TYPE_GREY:
  86759. use_grey = true;
  86760. break;
  86761. }
  86762. var pixel_data;
  86763. // var numAlphaBits = header.flags & 0xf;
  86764. var pixel_size = header.pixel_size >> 3;
  86765. var pixel_total = header.width * header.height * pixel_size;
  86766. // Read palettes
  86767. var palettes;
  86768. if (use_pal) {
  86769. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86770. }
  86771. // Read LRE
  86772. if (use_rle) {
  86773. pixel_data = new Uint8Array(pixel_total);
  86774. var c, count, i;
  86775. var localOffset = 0;
  86776. var pixels = new Uint8Array(pixel_size);
  86777. while (offset < pixel_total && localOffset < pixel_total) {
  86778. c = data[offset++];
  86779. count = (c & 0x7f) + 1;
  86780. // RLE pixels
  86781. if (c & 0x80) {
  86782. // Bind pixel tmp array
  86783. for (i = 0; i < pixel_size; ++i) {
  86784. pixels[i] = data[offset++];
  86785. }
  86786. // Copy pixel array
  86787. for (i = 0; i < count; ++i) {
  86788. pixel_data.set(pixels, localOffset + i * pixel_size);
  86789. }
  86790. localOffset += pixel_size * count;
  86791. }
  86792. // Raw pixels
  86793. else {
  86794. count *= pixel_size;
  86795. for (i = 0; i < count; ++i) {
  86796. pixel_data[localOffset + i] = data[offset++];
  86797. }
  86798. localOffset += count;
  86799. }
  86800. }
  86801. }
  86802. // RAW Pixels
  86803. else {
  86804. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86805. }
  86806. // Load to texture
  86807. var x_start, y_start, x_step, y_step, y_end, x_end;
  86808. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86809. default:
  86810. case TGATools._ORIGIN_UL:
  86811. x_start = 0;
  86812. x_step = 1;
  86813. x_end = header.width;
  86814. y_start = 0;
  86815. y_step = 1;
  86816. y_end = header.height;
  86817. break;
  86818. case TGATools._ORIGIN_BL:
  86819. x_start = 0;
  86820. x_step = 1;
  86821. x_end = header.width;
  86822. y_start = header.height - 1;
  86823. y_step = -1;
  86824. y_end = -1;
  86825. break;
  86826. case TGATools._ORIGIN_UR:
  86827. x_start = header.width - 1;
  86828. x_step = -1;
  86829. x_end = -1;
  86830. y_start = 0;
  86831. y_step = 1;
  86832. y_end = header.height;
  86833. break;
  86834. case TGATools._ORIGIN_BR:
  86835. x_start = header.width - 1;
  86836. x_step = -1;
  86837. x_end = -1;
  86838. y_start = header.height - 1;
  86839. y_step = -1;
  86840. y_end = -1;
  86841. break;
  86842. }
  86843. // Load the specify method
  86844. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86845. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86846. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  86847. };
  86848. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86849. var image = pixel_data, colormap = palettes;
  86850. var width = header.width, height = header.height;
  86851. var color, i = 0, x, y;
  86852. var imageData = new Uint8Array(width * height * 4);
  86853. for (y = y_start; y !== y_end; y += y_step) {
  86854. for (x = x_start; x !== x_end; x += x_step, i++) {
  86855. color = image[i];
  86856. imageData[(x + width * y) * 4 + 3] = 255;
  86857. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86858. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86859. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86860. }
  86861. }
  86862. return imageData;
  86863. };
  86864. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86865. var image = pixel_data;
  86866. var width = header.width, height = header.height;
  86867. var color, i = 0, x, y;
  86868. var imageData = new Uint8Array(width * height * 4);
  86869. for (y = y_start; y !== y_end; y += y_step) {
  86870. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86871. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86872. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86873. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86874. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86875. imageData[(x + width * y) * 4 + 0] = r;
  86876. imageData[(x + width * y) * 4 + 1] = g;
  86877. imageData[(x + width * y) * 4 + 2] = b;
  86878. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86879. }
  86880. }
  86881. return imageData;
  86882. };
  86883. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86884. var image = pixel_data;
  86885. var width = header.width, height = header.height;
  86886. var i = 0, x, y;
  86887. var imageData = new Uint8Array(width * height * 4);
  86888. for (y = y_start; y !== y_end; y += y_step) {
  86889. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86890. imageData[(x + width * y) * 4 + 3] = 255;
  86891. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86892. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86893. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86894. }
  86895. }
  86896. return imageData;
  86897. };
  86898. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86899. var image = pixel_data;
  86900. var width = header.width, height = header.height;
  86901. var i = 0, x, y;
  86902. var imageData = new Uint8Array(width * height * 4);
  86903. for (y = y_start; y !== y_end; y += y_step) {
  86904. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86905. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86906. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86907. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86908. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  86909. }
  86910. }
  86911. return imageData;
  86912. };
  86913. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86914. var image = pixel_data;
  86915. var width = header.width, height = header.height;
  86916. var color, i = 0, x, y;
  86917. var imageData = new Uint8Array(width * height * 4);
  86918. for (y = y_start; y !== y_end; y += y_step) {
  86919. for (x = x_start; x !== x_end; x += x_step, i++) {
  86920. color = image[i];
  86921. imageData[(x + width * y) * 4 + 0] = color;
  86922. imageData[(x + width * y) * 4 + 1] = color;
  86923. imageData[(x + width * y) * 4 + 2] = color;
  86924. imageData[(x + width * y) * 4 + 3] = 255;
  86925. }
  86926. }
  86927. return imageData;
  86928. };
  86929. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86930. var image = pixel_data;
  86931. var width = header.width, height = header.height;
  86932. var i = 0, x, y;
  86933. var imageData = new Uint8Array(width * height * 4);
  86934. for (y = y_start; y !== y_end; y += y_step) {
  86935. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86936. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  86937. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  86938. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86939. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  86940. }
  86941. }
  86942. return imageData;
  86943. };
  86944. //private static _TYPE_NO_DATA = 0;
  86945. TGATools._TYPE_INDEXED = 1;
  86946. TGATools._TYPE_RGB = 2;
  86947. TGATools._TYPE_GREY = 3;
  86948. TGATools._TYPE_RLE_INDEXED = 9;
  86949. TGATools._TYPE_RLE_RGB = 10;
  86950. TGATools._TYPE_RLE_GREY = 11;
  86951. TGATools._ORIGIN_MASK = 0x30;
  86952. TGATools._ORIGIN_SHIFT = 0x04;
  86953. TGATools._ORIGIN_BL = 0x00;
  86954. TGATools._ORIGIN_BR = 0x01;
  86955. TGATools._ORIGIN_UL = 0x02;
  86956. TGATools._ORIGIN_UR = 0x03;
  86957. return TGATools;
  86958. }());
  86959. BABYLON.TGATools = TGATools;
  86960. })(BABYLON || (BABYLON = {}));
  86961. //# sourceMappingURL=babylon.tga.js.map
  86962. var BABYLON;
  86963. (function (BABYLON) {
  86964. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  86965. // All values and structures referenced from:
  86966. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  86967. var DDS_MAGIC = 0x20534444;
  86968. var
  86969. //DDSD_CAPS = 0x1,
  86970. //DDSD_HEIGHT = 0x2,
  86971. //DDSD_WIDTH = 0x4,
  86972. //DDSD_PITCH = 0x8,
  86973. //DDSD_PIXELFORMAT = 0x1000,
  86974. DDSD_MIPMAPCOUNT = 0x20000;
  86975. //DDSD_LINEARSIZE = 0x80000,
  86976. //DDSD_DEPTH = 0x800000;
  86977. // var DDSCAPS_COMPLEX = 0x8,
  86978. // DDSCAPS_MIPMAP = 0x400000,
  86979. // DDSCAPS_TEXTURE = 0x1000;
  86980. var DDSCAPS2_CUBEMAP = 0x200;
  86981. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  86982. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  86983. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  86984. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  86985. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  86986. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  86987. // DDSCAPS2_VOLUME = 0x200000;
  86988. var
  86989. //DDPF_ALPHAPIXELS = 0x1,
  86990. //DDPF_ALPHA = 0x2,
  86991. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  86992. //DDPF_YUV = 0x200,
  86993. DDPF_LUMINANCE = 0x20000;
  86994. function FourCCToInt32(value) {
  86995. return value.charCodeAt(0) +
  86996. (value.charCodeAt(1) << 8) +
  86997. (value.charCodeAt(2) << 16) +
  86998. (value.charCodeAt(3) << 24);
  86999. }
  87000. function Int32ToFourCC(value) {
  87001. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  87002. }
  87003. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  87004. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  87005. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  87006. var FOURCC_DX10 = FourCCToInt32("DX10");
  87007. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  87008. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  87009. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  87010. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  87011. var headerLengthInt = 31; // The header length in 32 bit ints
  87012. // Offsets into the header array
  87013. var off_magic = 0;
  87014. var off_size = 1;
  87015. var off_flags = 2;
  87016. var off_height = 3;
  87017. var off_width = 4;
  87018. var off_mipmapCount = 7;
  87019. var off_pfFlags = 20;
  87020. var off_pfFourCC = 21;
  87021. var off_RGBbpp = 22;
  87022. var off_RMask = 23;
  87023. var off_GMask = 24;
  87024. var off_BMask = 25;
  87025. var off_AMask = 26;
  87026. // var off_caps1 = 27;
  87027. var off_caps2 = 28;
  87028. // var off_caps3 = 29;
  87029. // var off_caps4 = 30;
  87030. var off_dxgiFormat = 32;
  87031. ;
  87032. var DDSTools = /** @class */ (function () {
  87033. function DDSTools() {
  87034. }
  87035. DDSTools.GetDDSInfo = function (arrayBuffer) {
  87036. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87037. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  87038. var mipmapCount = 1;
  87039. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  87040. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87041. }
  87042. var fourCC = header[off_pfFourCC];
  87043. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  87044. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87045. switch (fourCC) {
  87046. case FOURCC_D3DFMT_R16G16B16A16F:
  87047. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87048. break;
  87049. case FOURCC_D3DFMT_R32G32B32A32F:
  87050. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87051. break;
  87052. case FOURCC_DX10:
  87053. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  87054. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  87055. break;
  87056. }
  87057. }
  87058. return {
  87059. width: header[off_width],
  87060. height: header[off_height],
  87061. mipmapCount: mipmapCount,
  87062. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  87063. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  87064. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  87065. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  87066. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  87067. dxgiFormat: dxgiFormat,
  87068. textureType: textureType
  87069. };
  87070. };
  87071. DDSTools._ToHalfFloat = function (value) {
  87072. if (!DDSTools._FloatView) {
  87073. DDSTools._FloatView = new Float32Array(1);
  87074. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  87075. }
  87076. DDSTools._FloatView[0] = value;
  87077. var x = DDSTools._Int32View[0];
  87078. var bits = (x >> 16) & 0x8000; /* Get the sign */
  87079. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  87080. var e = (x >> 23) & 0xff; /* Using int is faster here */
  87081. /* If zero, or denormal, or exponent underflows too much for a denormal
  87082. * half, return signed zero. */
  87083. if (e < 103) {
  87084. return bits;
  87085. }
  87086. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  87087. if (e > 142) {
  87088. bits |= 0x7c00;
  87089. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  87090. * not Inf, so make sure we set one mantissa bit too. */
  87091. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  87092. return bits;
  87093. }
  87094. /* If exponent underflows but not too much, return a denormal */
  87095. if (e < 113) {
  87096. m |= 0x0800;
  87097. /* Extra rounding may overflow and set mantissa to 0 and exponent
  87098. * to 1, which is OK. */
  87099. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  87100. return bits;
  87101. }
  87102. bits |= ((e - 112) << 10) | (m >> 1);
  87103. bits += m & 1;
  87104. return bits;
  87105. };
  87106. DDSTools._FromHalfFloat = function (value) {
  87107. var s = (value & 0x8000) >> 15;
  87108. var e = (value & 0x7C00) >> 10;
  87109. var f = value & 0x03FF;
  87110. if (e === 0) {
  87111. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87112. }
  87113. else if (e == 0x1F) {
  87114. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87115. }
  87116. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87117. };
  87118. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87119. var destArray = new Float32Array(dataLength);
  87120. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87121. var index = 0;
  87122. for (var y = 0; y < height; y++) {
  87123. for (var x = 0; x < width; x++) {
  87124. var srcPos = (x + y * width) * 4;
  87125. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87126. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87127. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87128. if (DDSTools.StoreLODInAlphaChannel) {
  87129. destArray[index + 3] = lod;
  87130. }
  87131. else {
  87132. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87133. }
  87134. index += 4;
  87135. }
  87136. }
  87137. return destArray;
  87138. };
  87139. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87140. if (DDSTools.StoreLODInAlphaChannel) {
  87141. var destArray = new Uint16Array(dataLength);
  87142. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87143. var index = 0;
  87144. for (var y = 0; y < height; y++) {
  87145. for (var x = 0; x < width; x++) {
  87146. var srcPos = (x + y * width) * 4;
  87147. destArray[index] = srcData[srcPos];
  87148. destArray[index + 1] = srcData[srcPos + 1];
  87149. destArray[index + 2] = srcData[srcPos + 2];
  87150. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87151. index += 4;
  87152. }
  87153. }
  87154. return destArray;
  87155. }
  87156. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87157. };
  87158. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87159. if (DDSTools.StoreLODInAlphaChannel) {
  87160. var destArray = new Float32Array(dataLength);
  87161. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87162. var index = 0;
  87163. for (var y = 0; y < height; y++) {
  87164. for (var x = 0; x < width; x++) {
  87165. var srcPos = (x + y * width) * 4;
  87166. destArray[index] = srcData[srcPos];
  87167. destArray[index + 1] = srcData[srcPos + 1];
  87168. destArray[index + 2] = srcData[srcPos + 2];
  87169. destArray[index + 3] = lod;
  87170. index += 4;
  87171. }
  87172. }
  87173. return destArray;
  87174. }
  87175. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87176. };
  87177. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87178. var destArray = new Uint8Array(dataLength);
  87179. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87180. var index = 0;
  87181. for (var y = 0; y < height; y++) {
  87182. for (var x = 0; x < width; x++) {
  87183. var srcPos = (x + y * width) * 4;
  87184. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87185. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87186. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87187. if (DDSTools.StoreLODInAlphaChannel) {
  87188. destArray[index + 3] = lod;
  87189. }
  87190. else {
  87191. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87192. }
  87193. index += 4;
  87194. }
  87195. }
  87196. return destArray;
  87197. };
  87198. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87199. var destArray = new Uint8Array(dataLength);
  87200. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87201. var index = 0;
  87202. for (var y = 0; y < height; y++) {
  87203. for (var x = 0; x < width; x++) {
  87204. var srcPos = (x + y * width) * 4;
  87205. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87206. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87207. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87208. if (DDSTools.StoreLODInAlphaChannel) {
  87209. destArray[index + 3] = lod;
  87210. }
  87211. else {
  87212. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87213. }
  87214. index += 4;
  87215. }
  87216. }
  87217. return destArray;
  87218. };
  87219. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87220. var byteArray = new Uint8Array(dataLength);
  87221. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87222. var index = 0;
  87223. for (var y = 0; y < height; y++) {
  87224. for (var x = 0; x < width; x++) {
  87225. var srcPos = (x + y * width) * 4;
  87226. byteArray[index] = srcData[srcPos + rOffset];
  87227. byteArray[index + 1] = srcData[srcPos + gOffset];
  87228. byteArray[index + 2] = srcData[srcPos + bOffset];
  87229. byteArray[index + 3] = srcData[srcPos + aOffset];
  87230. index += 4;
  87231. }
  87232. }
  87233. return byteArray;
  87234. };
  87235. DDSTools._ExtractLongWordOrder = function (value) {
  87236. if (value === 0 || value === 255 || value === -16777216) {
  87237. return 0;
  87238. }
  87239. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87240. };
  87241. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87242. var byteArray = new Uint8Array(dataLength);
  87243. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87244. var index = 0;
  87245. for (var y = 0; y < height; y++) {
  87246. for (var x = 0; x < width; x++) {
  87247. var srcPos = (x + y * width) * 3;
  87248. byteArray[index] = srcData[srcPos + rOffset];
  87249. byteArray[index + 1] = srcData[srcPos + gOffset];
  87250. byteArray[index + 2] = srcData[srcPos + bOffset];
  87251. index += 3;
  87252. }
  87253. }
  87254. return byteArray;
  87255. };
  87256. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87257. var byteArray = new Uint8Array(dataLength);
  87258. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87259. var index = 0;
  87260. for (var y = 0; y < height; y++) {
  87261. for (var x = 0; x < width; x++) {
  87262. var srcPos = (x + y * width);
  87263. byteArray[index] = srcData[srcPos];
  87264. index++;
  87265. }
  87266. }
  87267. return byteArray;
  87268. };
  87269. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87270. if (lodIndex === void 0) { lodIndex = -1; }
  87271. var sphericalPolynomialFaces = null;
  87272. if (info.sphericalPolynomial) {
  87273. sphericalPolynomialFaces = new Array();
  87274. }
  87275. var ext = engine.getCaps().s3tc;
  87276. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87277. var fourCC, width, height, dataLength = 0, dataOffset;
  87278. var byteArray, mipmapCount, mip;
  87279. var internalFormat = 0;
  87280. var format = 0;
  87281. var blockBytes = 1;
  87282. if (header[off_magic] !== DDS_MAGIC) {
  87283. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87284. return;
  87285. }
  87286. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87287. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87288. return;
  87289. }
  87290. if (info.isCompressed && !ext) {
  87291. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87292. return;
  87293. }
  87294. var bpp = header[off_RGBbpp];
  87295. dataOffset = header[off_size] + 4;
  87296. var computeFormats = false;
  87297. if (info.isFourCC) {
  87298. fourCC = header[off_pfFourCC];
  87299. switch (fourCC) {
  87300. case FOURCC_DXT1:
  87301. blockBytes = 8;
  87302. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87303. break;
  87304. case FOURCC_DXT3:
  87305. blockBytes = 16;
  87306. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87307. break;
  87308. case FOURCC_DXT5:
  87309. blockBytes = 16;
  87310. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87311. break;
  87312. case FOURCC_D3DFMT_R16G16B16A16F:
  87313. computeFormats = true;
  87314. break;
  87315. case FOURCC_D3DFMT_R32G32B32A32F:
  87316. computeFormats = true;
  87317. break;
  87318. case FOURCC_DX10:
  87319. // There is an additionnal header so dataOffset need to be changed
  87320. dataOffset += 5 * 4; // 5 uints
  87321. var supported = false;
  87322. switch (info.dxgiFormat) {
  87323. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87324. computeFormats = true;
  87325. supported = true;
  87326. break;
  87327. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87328. info.isRGB = true;
  87329. info.isFourCC = false;
  87330. bpp = 32;
  87331. supported = true;
  87332. break;
  87333. }
  87334. if (supported) {
  87335. break;
  87336. }
  87337. default:
  87338. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87339. return;
  87340. }
  87341. }
  87342. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87343. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87344. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87345. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87346. if (computeFormats) {
  87347. format = engine._getWebGLTextureType(info.textureType);
  87348. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87349. }
  87350. mipmapCount = 1;
  87351. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87352. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87353. }
  87354. for (var face = 0; face < faces; face++) {
  87355. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  87356. width = header[off_width];
  87357. height = header[off_height];
  87358. for (mip = 0; mip < mipmapCount; ++mip) {
  87359. if (lodIndex === -1 || lodIndex === mip) {
  87360. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87361. var i = (lodIndex === -1) ? mip : 0;
  87362. if (!info.isCompressed && info.isFourCC) {
  87363. dataLength = width * height * 4;
  87364. var floatArray = null;
  87365. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87366. if (bpp === 128) {
  87367. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87368. if (sphericalPolynomialFaces && i == 0) {
  87369. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87370. }
  87371. }
  87372. else if (bpp === 64) {
  87373. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87374. if (sphericalPolynomialFaces && i == 0) {
  87375. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87376. }
  87377. }
  87378. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87379. format = engine._getWebGLTextureType(info.textureType);
  87380. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87381. }
  87382. else {
  87383. if (bpp === 128) {
  87384. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87385. if (sphericalPolynomialFaces && i == 0) {
  87386. sphericalPolynomialFaces.push(floatArray);
  87387. }
  87388. }
  87389. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87390. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87391. if (sphericalPolynomialFaces && i == 0) {
  87392. sphericalPolynomialFaces.push(floatArray);
  87393. }
  87394. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87395. format = engine._getWebGLTextureType(info.textureType);
  87396. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87397. }
  87398. else { // 64
  87399. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87400. if (sphericalPolynomialFaces && i == 0) {
  87401. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87402. }
  87403. }
  87404. }
  87405. if (floatArray) {
  87406. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  87407. }
  87408. }
  87409. else if (info.isRGB) {
  87410. if (bpp === 24) {
  87411. dataLength = width * height * 3;
  87412. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87413. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  87414. }
  87415. else { // 32
  87416. dataLength = width * height * 4;
  87417. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87418. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  87419. }
  87420. }
  87421. else if (info.isLuminance) {
  87422. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  87423. var unpaddedRowSize = width;
  87424. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87425. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87426. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87427. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  87428. }
  87429. else {
  87430. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87431. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87432. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  87433. }
  87434. }
  87435. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87436. width *= 0.5;
  87437. height *= 0.5;
  87438. width = Math.max(1.0, width);
  87439. height = Math.max(1.0, height);
  87440. }
  87441. if (currentFace !== undefined) {
  87442. // Loading a single face
  87443. break;
  87444. }
  87445. }
  87446. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87447. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87448. size: header[off_width],
  87449. right: sphericalPolynomialFaces[0],
  87450. left: sphericalPolynomialFaces[1],
  87451. up: sphericalPolynomialFaces[2],
  87452. down: sphericalPolynomialFaces[3],
  87453. front: sphericalPolynomialFaces[4],
  87454. back: sphericalPolynomialFaces[5],
  87455. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87456. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87457. gammaSpace: false,
  87458. });
  87459. }
  87460. else {
  87461. info.sphericalPolynomial = undefined;
  87462. }
  87463. };
  87464. DDSTools.StoreLODInAlphaChannel = false;
  87465. return DDSTools;
  87466. }());
  87467. BABYLON.DDSTools = DDSTools;
  87468. })(BABYLON || (BABYLON = {}));
  87469. //# sourceMappingURL=babylon.dds.js.map
  87470. var BABYLON;
  87471. (function (BABYLON) {
  87472. /**
  87473. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87474. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87475. */
  87476. var KhronosTextureContainer = /** @class */ (function () {
  87477. /**
  87478. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87479. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87480. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87481. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87482. */
  87483. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87484. this.arrayBuffer = arrayBuffer;
  87485. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87486. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87487. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87488. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87489. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87490. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87491. BABYLON.Tools.Error("texture missing KTX identifier");
  87492. return;
  87493. }
  87494. // load the reset of the header in native 32 bit int
  87495. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87496. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87497. var oppositeEndianess = header[0] === 0x01020304;
  87498. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87499. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87500. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87501. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87502. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87503. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87504. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87505. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87506. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87507. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87508. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87509. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87510. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87511. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87512. if (this.glType !== 0) {
  87513. BABYLON.Tools.Error("only compressed formats currently supported");
  87514. return;
  87515. }
  87516. else {
  87517. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87518. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87519. }
  87520. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87521. BABYLON.Tools.Error("only 2D textures currently supported");
  87522. return;
  87523. }
  87524. if (this.numberOfArrayElements !== 0) {
  87525. BABYLON.Tools.Error("texture arrays not currently supported");
  87526. return;
  87527. }
  87528. if (this.numberOfFaces !== facesExpected) {
  87529. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87530. return;
  87531. }
  87532. // we now have a completely validated file, so could use existence of loadType as success
  87533. // would need to make this more elaborate & adjust checks above to support more than one load type
  87534. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87535. }
  87536. // not as fast hardware based, but will probably never need to use
  87537. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87538. return ((val & 0xFF) << 24)
  87539. | ((val & 0xFF00) << 8)
  87540. | ((val >> 8) & 0xFF00)
  87541. | ((val >> 24) & 0xFF);
  87542. };
  87543. /**
  87544. * It is assumed that the texture has already been created & is currently bound
  87545. */
  87546. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  87547. switch (this.loadType) {
  87548. case KhronosTextureContainer.COMPRESSED_2D:
  87549. this._upload2DCompressedLevels(gl, loadMipmaps);
  87550. break;
  87551. case KhronosTextureContainer.TEX_2D:
  87552. case KhronosTextureContainer.COMPRESSED_3D:
  87553. case KhronosTextureContainer.TEX_3D:
  87554. }
  87555. };
  87556. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  87557. // initialize width & height for level 1
  87558. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87559. var width = this.pixelWidth;
  87560. var height = this.pixelHeight;
  87561. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87562. for (var level = 0; level < mipmapCount; level++) {
  87563. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87564. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87565. for (var face = 0; face < this.numberOfFaces; face++) {
  87566. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  87567. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87568. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  87569. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87570. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87571. }
  87572. width = Math.max(1.0, width * 0.5);
  87573. height = Math.max(1.0, height * 0.5);
  87574. }
  87575. };
  87576. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87577. // load types
  87578. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87579. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87580. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87581. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87582. return KhronosTextureContainer;
  87583. }());
  87584. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87585. })(BABYLON || (BABYLON = {}));
  87586. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87587. var BABYLON;
  87588. (function (BABYLON) {
  87589. var Debug;
  87590. (function (Debug) {
  87591. /**
  87592. * Class used to render a debug view of a given skeleton
  87593. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87594. */
  87595. var SkeletonViewer = /** @class */ (function () {
  87596. /**
  87597. * Creates a new SkeletonViewer
  87598. * @param skeleton defines the skeleton to render
  87599. * @param mesh defines the mesh attached to the skeleton
  87600. * @param scene defines the hosting scene
  87601. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87602. * @param renderingGroupId defines the rendering group id to use with the viewer
  87603. */
  87604. function SkeletonViewer(
  87605. /** defines the skeleton to render */
  87606. skeleton,
  87607. /** defines the mesh attached to the skeleton */
  87608. mesh, scene,
  87609. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87610. autoUpdateBonesMatrices,
  87611. /** defines the rendering group id to use with the viewer */
  87612. renderingGroupId) {
  87613. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87614. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87615. this.skeleton = skeleton;
  87616. this.mesh = mesh;
  87617. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87618. this.renderingGroupId = renderingGroupId;
  87619. /** Gets or sets the color used to render the skeleton */
  87620. this.color = BABYLON.Color3.White();
  87621. this._debugLines = new Array();
  87622. this._isEnabled = false;
  87623. this._scene = scene;
  87624. this.update();
  87625. this._renderFunction = this.update.bind(this);
  87626. }
  87627. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87628. get: function () {
  87629. return this._isEnabled;
  87630. },
  87631. /** Gets or sets a boolean indicating if the viewer is enabled */
  87632. set: function (value) {
  87633. if (this._isEnabled === value) {
  87634. return;
  87635. }
  87636. this._isEnabled = value;
  87637. if (value) {
  87638. this._scene.registerBeforeRender(this._renderFunction);
  87639. }
  87640. else {
  87641. this._scene.unregisterBeforeRender(this._renderFunction);
  87642. }
  87643. },
  87644. enumerable: true,
  87645. configurable: true
  87646. });
  87647. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87648. if (x === void 0) { x = 0; }
  87649. if (y === void 0) { y = 0; }
  87650. if (z === void 0) { z = 0; }
  87651. var tmat = BABYLON.Tmp.Matrix[0];
  87652. var parentBone = bone.getParent();
  87653. tmat.copyFrom(bone.getLocalMatrix());
  87654. if (x !== 0 || y !== 0 || z !== 0) {
  87655. var tmat2 = BABYLON.Tmp.Matrix[1];
  87656. BABYLON.Matrix.IdentityToRef(tmat2);
  87657. tmat2.m[12] = x;
  87658. tmat2.m[13] = y;
  87659. tmat2.m[14] = z;
  87660. tmat2.multiplyToRef(tmat, tmat);
  87661. }
  87662. if (parentBone) {
  87663. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87664. }
  87665. tmat.multiplyToRef(meshMat, tmat);
  87666. position.x = tmat.m[12];
  87667. position.y = tmat.m[13];
  87668. position.z = tmat.m[14];
  87669. };
  87670. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87671. var len = bones.length;
  87672. var meshPos = this.mesh.position;
  87673. for (var i = 0; i < len; i++) {
  87674. var bone = bones[i];
  87675. var points = this._debugLines[i];
  87676. if (!points) {
  87677. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87678. this._debugLines[i] = points;
  87679. }
  87680. this._getBonePosition(points[0], bone, meshMat);
  87681. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87682. points[0].subtractInPlace(meshPos);
  87683. points[1].subtractInPlace(meshPos);
  87684. }
  87685. };
  87686. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87687. var len = bones.length;
  87688. var boneNum = 0;
  87689. var meshPos = this.mesh.position;
  87690. for (var i = len - 1; i >= 0; i--) {
  87691. var childBone = bones[i];
  87692. var parentBone = childBone.getParent();
  87693. if (!parentBone) {
  87694. continue;
  87695. }
  87696. var points = this._debugLines[boneNum];
  87697. if (!points) {
  87698. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87699. this._debugLines[boneNum] = points;
  87700. }
  87701. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87702. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87703. points[0].subtractInPlace(meshPos);
  87704. points[1].subtractInPlace(meshPos);
  87705. boneNum++;
  87706. }
  87707. };
  87708. /** Update the viewer to sync with current skeleton state */
  87709. SkeletonViewer.prototype.update = function () {
  87710. if (this.autoUpdateBonesMatrices) {
  87711. this.skeleton.computeAbsoluteTransforms();
  87712. }
  87713. if (this.skeleton.bones[0].length === undefined) {
  87714. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87715. }
  87716. else {
  87717. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87718. }
  87719. if (!this._debugMesh) {
  87720. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87721. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87722. }
  87723. else {
  87724. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87725. }
  87726. this._debugMesh.position.copyFrom(this.mesh.position);
  87727. this._debugMesh.color = this.color;
  87728. };
  87729. /** Release associated resources */
  87730. SkeletonViewer.prototype.dispose = function () {
  87731. if (this._debugMesh) {
  87732. this.isEnabled = false;
  87733. this._debugMesh.dispose();
  87734. this._debugMesh = null;
  87735. }
  87736. };
  87737. return SkeletonViewer;
  87738. }());
  87739. Debug.SkeletonViewer = SkeletonViewer;
  87740. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87741. })(BABYLON || (BABYLON = {}));
  87742. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87743. /**
  87744. * Module Debug contains the (visual) components to debug a scene correctly
  87745. */
  87746. var BABYLON;
  87747. (function (BABYLON) {
  87748. var Debug;
  87749. (function (Debug) {
  87750. /**
  87751. * The Axes viewer will show 3 axes in a specific point in space
  87752. */
  87753. var AxesViewer = /** @class */ (function () {
  87754. /**
  87755. * Creates a new AxesViewer
  87756. * @param scene defines the hosting scene
  87757. * @param scaleLines defines a number used to scale line length (1 by default)
  87758. */
  87759. function AxesViewer(scene, scaleLines) {
  87760. if (scaleLines === void 0) { scaleLines = 1; }
  87761. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87762. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87763. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87764. /**
  87765. * Gets or sets a number used to scale line length
  87766. */
  87767. this.scaleLines = 1;
  87768. this.scaleLines = scaleLines;
  87769. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87770. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87771. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87772. this._xmesh.renderingGroupId = 2;
  87773. this._ymesh.renderingGroupId = 2;
  87774. this._zmesh.renderingGroupId = 2;
  87775. this._xmesh.material.checkReadyOnlyOnce = true;
  87776. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87777. this._ymesh.material.checkReadyOnlyOnce = true;
  87778. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87779. this._zmesh.material.checkReadyOnlyOnce = true;
  87780. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87781. this.scene = scene;
  87782. }
  87783. /**
  87784. * Force the viewer to update
  87785. * @param position defines the position of the viewer
  87786. * @param xaxis defines the x axis of the viewer
  87787. * @param yaxis defines the y axis of the viewer
  87788. * @param zaxis defines the z axis of the viewer
  87789. */
  87790. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87791. var scaleLines = this.scaleLines;
  87792. if (this._xmesh) {
  87793. this._xmesh.position.copyFrom(position);
  87794. }
  87795. if (this._ymesh) {
  87796. this._ymesh.position.copyFrom(position);
  87797. }
  87798. if (this._zmesh) {
  87799. this._zmesh.position.copyFrom(position);
  87800. }
  87801. var point2 = this._xline[1];
  87802. point2.x = xaxis.x * scaleLines;
  87803. point2.y = xaxis.y * scaleLines;
  87804. point2.z = xaxis.z * scaleLines;
  87805. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87806. point2 = this._yline[1];
  87807. point2.x = yaxis.x * scaleLines;
  87808. point2.y = yaxis.y * scaleLines;
  87809. point2.z = yaxis.z * scaleLines;
  87810. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87811. point2 = this._zline[1];
  87812. point2.x = zaxis.x * scaleLines;
  87813. point2.y = zaxis.y * scaleLines;
  87814. point2.z = zaxis.z * scaleLines;
  87815. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87816. };
  87817. /** Releases resources */
  87818. AxesViewer.prototype.dispose = function () {
  87819. if (this._xmesh) {
  87820. this._xmesh.dispose();
  87821. }
  87822. if (this._ymesh) {
  87823. this._ymesh.dispose();
  87824. }
  87825. if (this._zmesh) {
  87826. this._zmesh.dispose();
  87827. }
  87828. this._xmesh = null;
  87829. this._ymesh = null;
  87830. this._zmesh = null;
  87831. this.scene = null;
  87832. };
  87833. return AxesViewer;
  87834. }());
  87835. Debug.AxesViewer = AxesViewer;
  87836. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87837. })(BABYLON || (BABYLON = {}));
  87838. //# sourceMappingURL=babylon.axesViewer.js.map
  87839. var BABYLON;
  87840. (function (BABYLON) {
  87841. var Debug;
  87842. (function (Debug) {
  87843. /**
  87844. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87845. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87846. */
  87847. var BoneAxesViewer = /** @class */ (function (_super) {
  87848. __extends(BoneAxesViewer, _super);
  87849. /**
  87850. * Creates a new BoneAxesViewer
  87851. * @param scene defines the hosting scene
  87852. * @param bone defines the target bone
  87853. * @param mesh defines the target mesh
  87854. * @param scaleLines defines a scaling factor for line length (1 by default)
  87855. */
  87856. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87857. if (scaleLines === void 0) { scaleLines = 1; }
  87858. var _this = _super.call(this, scene, scaleLines) || this;
  87859. /** Gets current position */
  87860. _this.pos = BABYLON.Vector3.Zero();
  87861. /** Gets direction of X axis */
  87862. _this.xaxis = BABYLON.Vector3.Zero();
  87863. /** Gets direction of Y axis */
  87864. _this.yaxis = BABYLON.Vector3.Zero();
  87865. /** Gets direction of Z axis */
  87866. _this.zaxis = BABYLON.Vector3.Zero();
  87867. _this.mesh = mesh;
  87868. _this.bone = bone;
  87869. return _this;
  87870. }
  87871. /**
  87872. * Force the viewer to update
  87873. */
  87874. BoneAxesViewer.prototype.update = function () {
  87875. if (!this.mesh || !this.bone) {
  87876. return;
  87877. }
  87878. var bone = this.bone;
  87879. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87880. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87881. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87882. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87883. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87884. };
  87885. /** Releases resources */
  87886. BoneAxesViewer.prototype.dispose = function () {
  87887. if (this.mesh) {
  87888. this.mesh = null;
  87889. this.bone = null;
  87890. _super.prototype.dispose.call(this);
  87891. }
  87892. };
  87893. return BoneAxesViewer;
  87894. }(Debug.AxesViewer));
  87895. Debug.BoneAxesViewer = BoneAxesViewer;
  87896. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87897. })(BABYLON || (BABYLON = {}));
  87898. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  87899. var BABYLON;
  87900. (function (BABYLON) {
  87901. var RayHelper = /** @class */ (function () {
  87902. function RayHelper(ray) {
  87903. this.ray = ray;
  87904. }
  87905. RayHelper.CreateAndShow = function (ray, scene, color) {
  87906. var helper = new RayHelper(ray);
  87907. helper.show(scene, color);
  87908. return helper;
  87909. };
  87910. RayHelper.prototype.show = function (scene, color) {
  87911. if (!this._renderFunction && this.ray) {
  87912. var ray = this.ray;
  87913. this._renderFunction = this._render.bind(this);
  87914. this._scene = scene;
  87915. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  87916. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  87917. if (this._renderFunction) {
  87918. this._scene.registerBeforeRender(this._renderFunction);
  87919. }
  87920. }
  87921. if (color && this._renderLine) {
  87922. this._renderLine.color.copyFrom(color);
  87923. }
  87924. };
  87925. RayHelper.prototype.hide = function () {
  87926. if (this._renderFunction && this._scene) {
  87927. this._scene.unregisterBeforeRender(this._renderFunction);
  87928. this._scene = null;
  87929. this._renderFunction = null;
  87930. if (this._renderLine) {
  87931. this._renderLine.dispose();
  87932. this._renderLine = null;
  87933. }
  87934. this._renderPoints = [];
  87935. }
  87936. };
  87937. RayHelper.prototype._render = function () {
  87938. var ray = this.ray;
  87939. if (!ray) {
  87940. return;
  87941. }
  87942. var point = this._renderPoints[1];
  87943. var len = Math.min(ray.length, 1000000);
  87944. point.copyFrom(ray.direction);
  87945. point.scaleInPlace(len);
  87946. point.addInPlace(ray.origin);
  87947. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  87948. };
  87949. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  87950. this._attachedToMesh = mesh;
  87951. var ray = this.ray;
  87952. if (!ray) {
  87953. return;
  87954. }
  87955. if (!ray.direction) {
  87956. ray.direction = BABYLON.Vector3.Zero();
  87957. }
  87958. if (!ray.origin) {
  87959. ray.origin = BABYLON.Vector3.Zero();
  87960. }
  87961. if (length) {
  87962. ray.length = length;
  87963. }
  87964. if (!meshSpaceOrigin) {
  87965. meshSpaceOrigin = BABYLON.Vector3.Zero();
  87966. }
  87967. if (!meshSpaceDirection) {
  87968. // -1 so that this will work with Mesh.lookAt
  87969. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  87970. }
  87971. if (!this._meshSpaceDirection) {
  87972. this._meshSpaceDirection = meshSpaceDirection.clone();
  87973. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  87974. }
  87975. else {
  87976. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  87977. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  87978. }
  87979. if (!this._updateToMeshFunction) {
  87980. this._updateToMeshFunction = this._updateToMesh.bind(this);
  87981. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  87982. }
  87983. this._updateToMesh();
  87984. };
  87985. RayHelper.prototype.detachFromMesh = function () {
  87986. if (this._attachedToMesh) {
  87987. if (this._updateToMeshFunction) {
  87988. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  87989. }
  87990. this._attachedToMesh = null;
  87991. this._updateToMeshFunction = null;
  87992. }
  87993. };
  87994. RayHelper.prototype._updateToMesh = function () {
  87995. var ray = this.ray;
  87996. if (!this._attachedToMesh || !ray) {
  87997. return;
  87998. }
  87999. if (this._attachedToMesh._isDisposed) {
  88000. this.detachFromMesh();
  88001. return;
  88002. }
  88003. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  88004. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  88005. };
  88006. RayHelper.prototype.dispose = function () {
  88007. this.hide();
  88008. this.detachFromMesh();
  88009. this.ray = null;
  88010. };
  88011. return RayHelper;
  88012. }());
  88013. BABYLON.RayHelper = RayHelper;
  88014. })(BABYLON || (BABYLON = {}));
  88015. //# sourceMappingURL=babylon.rayHelper.js.map
  88016. var BABYLON;
  88017. (function (BABYLON) {
  88018. // load the inspector using require, if not present in the global namespace.
  88019. var DebugLayer = /** @class */ (function () {
  88020. function DebugLayer(scene) {
  88021. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88022. this._scene = scene;
  88023. // load inspector using require, if it doesn't exist on the global namespace.
  88024. }
  88025. /** Creates the inspector window. */
  88026. DebugLayer.prototype._createInspector = function (config) {
  88027. if (config === void 0) { config = {}; }
  88028. var popup = config.popup || false;
  88029. var initialTab = config.initialTab || 0;
  88030. var parentElement = config.parentElement || null;
  88031. if (!this._inspector) {
  88032. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  88033. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  88034. } // else nothing to do,; instance is already existing
  88035. };
  88036. DebugLayer.prototype.isVisible = function () {
  88037. if (!this._inspector) {
  88038. return false;
  88039. }
  88040. return true;
  88041. };
  88042. DebugLayer.prototype.hide = function () {
  88043. if (this._inspector) {
  88044. try {
  88045. this._inspector.dispose();
  88046. }
  88047. catch (e) {
  88048. // If the inspector has been removed directly from the inspector tool
  88049. }
  88050. this.onPropertyChangedObservable.clear();
  88051. this._inspector = null;
  88052. }
  88053. };
  88054. /**
  88055. *
  88056. * Launch the debugLayer.
  88057. *
  88058. * initialTab:
  88059. * | Value | Tab Name |
  88060. * | --- | --- |
  88061. * | 0 | Scene |
  88062. * | 1 | Console |
  88063. * | 2 | Stats |
  88064. * | 3 | Textures |
  88065. * | 4 | Mesh |
  88066. * | 5 | Light |
  88067. * | 6 | Material |
  88068. * | 7 | GLTF |
  88069. * | 8 | GUI |
  88070. * | 9 | Physics |
  88071. * | 10 | Camera |
  88072. * | 11 | Audio |
  88073. *
  88074. */
  88075. DebugLayer.prototype.show = function (config) {
  88076. if (config === void 0) { config = {}; }
  88077. if (typeof this.BJSINSPECTOR == 'undefined') {
  88078. // Load inspector and add it to the DOM
  88079. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  88080. }
  88081. else {
  88082. // Otherwise creates the inspector
  88083. this._createInspector(config);
  88084. this.onPropertyChangedObservable = new BABYLON.Observable();
  88085. }
  88086. };
  88087. /**
  88088. * Gets the active tab
  88089. * @return the index of the active tab or -1 if the inspector is hidden
  88090. */
  88091. DebugLayer.prototype.getActiveTab = function () {
  88092. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  88093. };
  88094. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  88095. return DebugLayer;
  88096. }());
  88097. BABYLON.DebugLayer = DebugLayer;
  88098. })(BABYLON || (BABYLON = {}));
  88099. //# sourceMappingURL=babylon.debugLayer.js.map
  88100. var BABYLON;
  88101. (function (BABYLON) {
  88102. var Debug;
  88103. (function (Debug) {
  88104. /**
  88105. * Used to show the physics impostor around the specific mesh
  88106. */
  88107. var PhysicsViewer = /** @class */ (function () {
  88108. /**
  88109. * Creates a new PhysicsViewer
  88110. * @param scene defines the hosting scene
  88111. */
  88112. function PhysicsViewer(scene) {
  88113. /** @hidden */
  88114. this._impostors = [];
  88115. /** @hidden */
  88116. this._meshes = [];
  88117. /** @hidden */
  88118. this._numMeshes = 0;
  88119. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88120. var physicEngine = this._scene.getPhysicsEngine();
  88121. if (physicEngine) {
  88122. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  88123. }
  88124. }
  88125. /** @hidden */
  88126. PhysicsViewer.prototype._updateDebugMeshes = function () {
  88127. var plugin = this._physicsEnginePlugin;
  88128. for (var i = 0; i < this._numMeshes; i++) {
  88129. var impostor = this._impostors[i];
  88130. if (!impostor) {
  88131. continue;
  88132. }
  88133. if (impostor.isDisposed) {
  88134. this.hideImpostor(this._impostors[i--]);
  88135. }
  88136. else {
  88137. var mesh = this._meshes[i];
  88138. if (mesh && plugin) {
  88139. plugin.syncMeshWithImpostor(mesh, impostor);
  88140. }
  88141. }
  88142. }
  88143. };
  88144. /**
  88145. * Renders a specified physic impostor
  88146. * @param impostor defines the impostor to render
  88147. */
  88148. PhysicsViewer.prototype.showImpostor = function (impostor) {
  88149. if (!this._scene) {
  88150. return;
  88151. }
  88152. for (var i = 0; i < this._numMeshes; i++) {
  88153. if (this._impostors[i] == impostor) {
  88154. return;
  88155. }
  88156. }
  88157. var debugMesh = this._getDebugMesh(impostor, this._scene);
  88158. if (debugMesh) {
  88159. this._impostors[this._numMeshes] = impostor;
  88160. this._meshes[this._numMeshes] = debugMesh;
  88161. if (this._numMeshes === 0) {
  88162. this._renderFunction = this._updateDebugMeshes.bind(this);
  88163. this._scene.registerBeforeRender(this._renderFunction);
  88164. }
  88165. this._numMeshes++;
  88166. }
  88167. };
  88168. /**
  88169. * Hides a specified physic impostor
  88170. * @param impostor defines the impostor to hide
  88171. */
  88172. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  88173. if (!impostor || !this._scene) {
  88174. return;
  88175. }
  88176. var removed = false;
  88177. for (var i = 0; i < this._numMeshes; i++) {
  88178. if (this._impostors[i] == impostor) {
  88179. var mesh = this._meshes[i];
  88180. if (!mesh) {
  88181. continue;
  88182. }
  88183. this._scene.removeMesh(mesh);
  88184. mesh.dispose();
  88185. this._numMeshes--;
  88186. if (this._numMeshes > 0) {
  88187. this._meshes[i] = this._meshes[this._numMeshes];
  88188. this._impostors[i] = this._impostors[this._numMeshes];
  88189. this._meshes[this._numMeshes] = null;
  88190. this._impostors[this._numMeshes] = null;
  88191. }
  88192. else {
  88193. this._meshes[0] = null;
  88194. this._impostors[0] = null;
  88195. }
  88196. removed = true;
  88197. break;
  88198. }
  88199. }
  88200. if (removed && this._numMeshes === 0) {
  88201. this._scene.unregisterBeforeRender(this._renderFunction);
  88202. }
  88203. };
  88204. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  88205. if (!this._debugMaterial) {
  88206. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  88207. this._debugMaterial.wireframe = true;
  88208. }
  88209. return this._debugMaterial;
  88210. };
  88211. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  88212. if (!this._debugBoxMesh) {
  88213. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  88214. this._debugBoxMesh.renderingGroupId = 1;
  88215. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88216. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  88217. scene.removeMesh(this._debugBoxMesh);
  88218. }
  88219. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  88220. };
  88221. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  88222. if (!this._debugSphereMesh) {
  88223. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  88224. this._debugSphereMesh.renderingGroupId = 1;
  88225. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88226. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  88227. scene.removeMesh(this._debugSphereMesh);
  88228. }
  88229. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  88230. };
  88231. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  88232. var mesh = null;
  88233. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  88234. mesh = this._getDebugBoxMesh(scene);
  88235. impostor.getBoxSizeToRef(mesh.scaling);
  88236. }
  88237. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  88238. mesh = this._getDebugSphereMesh(scene);
  88239. var radius = impostor.getRadius();
  88240. mesh.scaling.x = radius * 2;
  88241. mesh.scaling.y = radius * 2;
  88242. mesh.scaling.z = radius * 2;
  88243. }
  88244. return mesh;
  88245. };
  88246. /** Releases all resources */
  88247. PhysicsViewer.prototype.dispose = function () {
  88248. for (var i = 0; i < this._numMeshes; i++) {
  88249. this.hideImpostor(this._impostors[i]);
  88250. }
  88251. if (this._debugBoxMesh) {
  88252. this._debugBoxMesh.dispose();
  88253. }
  88254. if (this._debugSphereMesh) {
  88255. this._debugSphereMesh.dispose();
  88256. }
  88257. if (this._debugMaterial) {
  88258. this._debugMaterial.dispose();
  88259. }
  88260. this._impostors.length = 0;
  88261. this._scene = null;
  88262. this._physicsEnginePlugin = null;
  88263. };
  88264. return PhysicsViewer;
  88265. }());
  88266. Debug.PhysicsViewer = PhysicsViewer;
  88267. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88268. })(BABYLON || (BABYLON = {}));
  88269. //# sourceMappingURL=babylon.physicsViewer.js.map
  88270. var BABYLON;
  88271. (function (BABYLON) {
  88272. var BoundingBoxRenderer = /** @class */ (function () {
  88273. function BoundingBoxRenderer(scene) {
  88274. this.frontColor = new BABYLON.Color3(1, 1, 1);
  88275. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  88276. this.showBackLines = true;
  88277. this.renderList = new BABYLON.SmartArray(32);
  88278. this._vertexBuffers = {};
  88279. this._scene = scene;
  88280. }
  88281. BoundingBoxRenderer.prototype._prepareRessources = function () {
  88282. if (this._colorShader) {
  88283. return;
  88284. }
  88285. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  88286. attributes: [BABYLON.VertexBuffer.PositionKind],
  88287. uniforms: ["world", "viewProjection", "color"]
  88288. });
  88289. var engine = this._scene.getEngine();
  88290. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  88291. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  88292. this._createIndexBuffer();
  88293. };
  88294. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  88295. var engine = this._scene.getEngine();
  88296. 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]);
  88297. };
  88298. BoundingBoxRenderer.prototype._rebuild = function () {
  88299. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88300. if (vb) {
  88301. vb._rebuild();
  88302. }
  88303. this._createIndexBuffer();
  88304. };
  88305. BoundingBoxRenderer.prototype.reset = function () {
  88306. this.renderList.reset();
  88307. };
  88308. BoundingBoxRenderer.prototype.render = function () {
  88309. if (this.renderList.length === 0) {
  88310. return;
  88311. }
  88312. this._prepareRessources();
  88313. if (!this._colorShader.isReady()) {
  88314. return;
  88315. }
  88316. var engine = this._scene.getEngine();
  88317. engine.setDepthWrite(false);
  88318. this._colorShader._preBind();
  88319. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  88320. var boundingBox = this.renderList.data[boundingBoxIndex];
  88321. var min = boundingBox.minimum;
  88322. var max = boundingBox.maximum;
  88323. var diff = max.subtract(min);
  88324. var median = min.add(diff.scale(0.5));
  88325. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88326. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88327. .multiply(boundingBox.getWorldMatrix());
  88328. // VBOs
  88329. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88330. if (this.showBackLines) {
  88331. // Back
  88332. engine.setDepthFunctionToGreaterOrEqual();
  88333. this._scene.resetCachedMaterial();
  88334. this._colorShader.setColor4("color", this.backColor.toColor4());
  88335. this._colorShader.bind(worldMatrix);
  88336. // Draw order
  88337. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88338. }
  88339. // Front
  88340. engine.setDepthFunctionToLess();
  88341. this._scene.resetCachedMaterial();
  88342. this._colorShader.setColor4("color", this.frontColor.toColor4());
  88343. this._colorShader.bind(worldMatrix);
  88344. // Draw order
  88345. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88346. }
  88347. this._colorShader.unbind();
  88348. engine.setDepthFunctionToLessOrEqual();
  88349. engine.setDepthWrite(true);
  88350. };
  88351. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88352. this._prepareRessources();
  88353. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88354. return;
  88355. }
  88356. var engine = this._scene.getEngine();
  88357. engine.setDepthWrite(false);
  88358. engine.setColorWrite(false);
  88359. this._colorShader._preBind();
  88360. var boundingBox = mesh._boundingInfo.boundingBox;
  88361. var min = boundingBox.minimum;
  88362. var max = boundingBox.maximum;
  88363. var diff = max.subtract(min);
  88364. var median = min.add(diff.scale(0.5));
  88365. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88366. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88367. .multiply(boundingBox.getWorldMatrix());
  88368. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88369. engine.setDepthFunctionToLess();
  88370. this._scene.resetCachedMaterial();
  88371. this._colorShader.bind(worldMatrix);
  88372. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88373. this._colorShader.unbind();
  88374. engine.setDepthFunctionToLessOrEqual();
  88375. engine.setDepthWrite(true);
  88376. engine.setColorWrite(true);
  88377. };
  88378. BoundingBoxRenderer.prototype.dispose = function () {
  88379. if (!this._colorShader) {
  88380. return;
  88381. }
  88382. this.renderList.dispose();
  88383. this._colorShader.dispose();
  88384. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88385. if (buffer) {
  88386. buffer.dispose();
  88387. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88388. }
  88389. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88390. };
  88391. return BoundingBoxRenderer;
  88392. }());
  88393. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88394. })(BABYLON || (BABYLON = {}));
  88395. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88396. var BABYLON;
  88397. (function (BABYLON) {
  88398. /**
  88399. * Renders a layer on top of an existing scene
  88400. */
  88401. var UtilityLayerRenderer = /** @class */ (function () {
  88402. /**
  88403. * Instantiates a UtilityLayerRenderer
  88404. * @param originalScene the original scene that will be rendered on top of
  88405. */
  88406. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88407. var _this = this;
  88408. this.originalScene = originalScene;
  88409. this._pointerCaptures = {};
  88410. this._lastPointerEvents = {};
  88411. /**
  88412. * If the utility layer should automatically be rendered on top of existing scene
  88413. */
  88414. this.shouldRender = true;
  88415. /**
  88416. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88417. */
  88418. this.onlyCheckPointerDownEvents = true;
  88419. /**
  88420. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88421. */
  88422. this.processAllEvents = false;
  88423. /**
  88424. * Observable raised when the pointer move from the utility layer scene to the main scene
  88425. */
  88426. this.onPointerOutObservable = new BABYLON.Observable();
  88427. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88428. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88429. originalScene.getEngine().scenes.pop();
  88430. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88431. this.utilityLayerScene.detachControl();
  88432. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88433. if (!_this.processAllEvents) {
  88434. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88435. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88436. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88437. return;
  88438. }
  88439. }
  88440. var pointerEvent = (prePointerInfo.event);
  88441. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88442. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88443. return;
  88444. }
  88445. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88446. if (!prePointerInfo.ray && utilityScenePick) {
  88447. prePointerInfo.ray = utilityScenePick.ray;
  88448. }
  88449. // always fire the prepointer oversvable
  88450. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88451. // allow every non pointer down event to flow to the utility layer
  88452. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88453. if (!prePointerInfo.skipOnPointerObservable) {
  88454. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88455. }
  88456. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88457. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88458. }
  88459. return;
  88460. }
  88461. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88462. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88463. if (utilityScenePick && utilityScenePick.hit) {
  88464. if (!prePointerInfo.skipOnPointerObservable) {
  88465. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88466. }
  88467. prePointerInfo.skipOnPointerObservable = true;
  88468. }
  88469. }
  88470. else {
  88471. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88472. var pointerEvent_1 = (prePointerInfo.event);
  88473. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88474. if (originalScenePick && utilityScenePick) {
  88475. // No pick in utility scene
  88476. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88477. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88478. // We touched an utility mesh present in the main scene
  88479. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88480. prePointerInfo.skipOnPointerObservable = true;
  88481. }
  88482. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88483. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88484. }
  88485. }
  88486. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88487. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88488. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88489. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88490. }
  88491. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88492. // We have a pick in both scenes but main is closer than utility
  88493. // We touched an utility mesh present in the main scene
  88494. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88495. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88496. prePointerInfo.skipOnPointerObservable = true;
  88497. }
  88498. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88499. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88500. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88501. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88502. }
  88503. }
  88504. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88505. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88506. }
  88507. }
  88508. }
  88509. });
  88510. // Render directly on top of existing scene without clearing
  88511. this.utilityLayerScene.autoClear = false;
  88512. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88513. if (_this.shouldRender) {
  88514. _this.render();
  88515. }
  88516. });
  88517. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88518. _this.dispose();
  88519. });
  88520. this._updateCamera();
  88521. }
  88522. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88523. get: function () {
  88524. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88525. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88526. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88527. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88528. });
  88529. }
  88530. return UtilityLayerRenderer._DefaultUtilityLayer;
  88531. },
  88532. enumerable: true,
  88533. configurable: true
  88534. });
  88535. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88536. if (!prePointerInfo.skipOnPointerObservable) {
  88537. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88538. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88539. }
  88540. };
  88541. /**
  88542. * Renders the utility layers scene on top of the original scene
  88543. */
  88544. UtilityLayerRenderer.prototype.render = function () {
  88545. this._updateCamera();
  88546. this.utilityLayerScene.render(false);
  88547. };
  88548. /**
  88549. * Disposes of the renderer
  88550. */
  88551. UtilityLayerRenderer.prototype.dispose = function () {
  88552. this.onPointerOutObservable.clear();
  88553. if (this._afterRenderObserver) {
  88554. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88555. }
  88556. if (this._sceneDisposeObserver) {
  88557. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88558. }
  88559. if (this._originalPointerObserver) {
  88560. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88561. }
  88562. this.utilityLayerScene.dispose();
  88563. };
  88564. UtilityLayerRenderer.prototype._updateCamera = function () {
  88565. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88566. };
  88567. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88568. return UtilityLayerRenderer;
  88569. }());
  88570. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88571. })(BABYLON || (BABYLON = {}));
  88572. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88573. //# sourceMappingURL=babylon.behavior.js.map
  88574. var BABYLON;
  88575. (function (BABYLON) {
  88576. /**
  88577. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88578. */
  88579. var PointerDragBehavior = /** @class */ (function () {
  88580. /**
  88581. * Creates a pointer drag behavior that can be attached to a mesh
  88582. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  88583. */
  88584. function PointerDragBehavior(options) {
  88585. this.options = options;
  88586. /**
  88587. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88588. */
  88589. this.currentDraggingPointerID = -1;
  88590. /**
  88591. * If the behavior is currently in a dragging state
  88592. */
  88593. this.dragging = false;
  88594. /**
  88595. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  88596. */
  88597. this.dragDeltaRatio = 0.2;
  88598. /**
  88599. * If the drag plane orientation should be updated during the dragging (Default: true)
  88600. */
  88601. this.updateDragPlane = true;
  88602. // Debug mode will display drag planes to help visualize behavior
  88603. this._debugMode = false;
  88604. this._moving = false;
  88605. /**
  88606. * Fires each time the attached mesh is dragged with the pointer
  88607. * * delta between last drag position and current drag position in world space
  88608. * * dragDistance along the drag axis
  88609. * * dragPlaneNormal normal of the current drag plane used during the drag
  88610. * * dragPlanePoint in world space where the drag intersects the drag plane
  88611. */
  88612. this.onDragObservable = new BABYLON.Observable();
  88613. /**
  88614. * Fires each time a drag begins (eg. mouse down on mesh)
  88615. */
  88616. this.onDragStartObservable = new BABYLON.Observable();
  88617. /**
  88618. * Fires each time a drag ends (eg. mouse release after drag)
  88619. */
  88620. this.onDragEndObservable = new BABYLON.Observable();
  88621. /**
  88622. * If the attached mesh should be moved when dragged
  88623. */
  88624. this.moveAttached = true;
  88625. /**
  88626. * If the drag behavior will react to drag events (Default: true)
  88627. */
  88628. this.enabled = true;
  88629. /**
  88630. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88631. */
  88632. this.useObjectOrienationForDragging = true;
  88633. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88634. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88635. // Variables to avoid instantiation in the below method
  88636. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88637. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88638. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88639. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88640. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88641. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88642. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88643. var optionCount = 0;
  88644. if (options === undefined) {
  88645. options = {};
  88646. }
  88647. if (options.dragAxis) {
  88648. optionCount++;
  88649. }
  88650. if (options.dragPlaneNormal) {
  88651. optionCount++;
  88652. }
  88653. if (optionCount > 1) {
  88654. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88655. }
  88656. }
  88657. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88658. /**
  88659. * The name of the behavior
  88660. */
  88661. get: function () {
  88662. return "PointerDrag";
  88663. },
  88664. enumerable: true,
  88665. configurable: true
  88666. });
  88667. /**
  88668. * Initializes the behavior
  88669. */
  88670. PointerDragBehavior.prototype.init = function () { };
  88671. /**
  88672. * Attaches the drag behavior the passed in mesh
  88673. * @param ownerNode The mesh that will be dragged around once attached
  88674. */
  88675. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88676. var _this = this;
  88677. this._scene = ownerNode.getScene();
  88678. this._attachedNode = ownerNode;
  88679. // Initialize drag plane to not interfere with existing scene
  88680. if (!PointerDragBehavior._planeScene) {
  88681. if (this._debugMode) {
  88682. PointerDragBehavior._planeScene = this._scene;
  88683. }
  88684. else {
  88685. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88686. this._scene.getEngine().scenes.pop();
  88687. }
  88688. }
  88689. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88690. // State of the drag
  88691. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88692. var delta = new BABYLON.Vector3(0, 0, 0);
  88693. var dragLength = 0;
  88694. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88695. var pickPredicate = function (m) {
  88696. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88697. };
  88698. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88699. if (!_this.enabled) {
  88700. return;
  88701. }
  88702. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88703. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88704. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88705. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88706. if (pickedPoint) {
  88707. _this.dragging = true;
  88708. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88709. _this.lastDragPosition.copyFrom(pickedPoint);
  88710. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88711. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88712. }
  88713. }
  88714. }
  88715. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88716. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88717. _this.releaseDrag();
  88718. }
  88719. }
  88720. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88721. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88722. _this._moving = true;
  88723. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88724. if (pickedPoint) {
  88725. if (_this.updateDragPlane) {
  88726. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88727. }
  88728. // depending on the drag mode option drag accordingly
  88729. if (_this.options.dragAxis) {
  88730. // Convert local drag axis to world
  88731. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88732. // Project delta drag from the drag plane onto the drag axis
  88733. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88734. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88735. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88736. }
  88737. else {
  88738. dragLength = delta.length();
  88739. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88740. }
  88741. targetPosition.addInPlace(delta);
  88742. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88743. _this.lastDragPosition.copyFrom(pickedPoint);
  88744. }
  88745. }
  88746. }
  88747. });
  88748. this._scene.onBeforeRenderObservable.add(function () {
  88749. if (_this._moving && _this.moveAttached) {
  88750. // Slowly move mesh to avoid jitter
  88751. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88752. _this._tmpVector.scaleInPlace(0.2);
  88753. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88754. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88755. }
  88756. });
  88757. };
  88758. PointerDragBehavior.prototype.releaseDrag = function () {
  88759. this.dragging = false;
  88760. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88761. this.currentDraggingPointerID = -1;
  88762. this._moving = false;
  88763. };
  88764. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88765. var _this = this;
  88766. if (!ray) {
  88767. return null;
  88768. }
  88769. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88770. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88771. return pickResult.pickedPoint;
  88772. }
  88773. else {
  88774. return null;
  88775. }
  88776. };
  88777. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88778. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88779. this._pointA.copyFrom(dragPlanePosition);
  88780. if (this.options.dragAxis) {
  88781. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  88782. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88783. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88784. ray.origin.subtractToRef(this._pointA, this._pointC);
  88785. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88786. // Get perpendicular line from direction to camera and drag axis
  88787. this._pointB.subtractToRef(this._pointA, this._lineA);
  88788. this._pointC.subtractToRef(this._pointA, this._lineB);
  88789. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88790. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88791. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88792. this._lookAt.normalize();
  88793. this._dragPlane.position.copyFrom(this._pointA);
  88794. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88795. this._dragPlane.lookAt(this._lookAt);
  88796. }
  88797. else if (this.options.dragPlaneNormal) {
  88798. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  88799. this._dragPlane.position.copyFrom(this._pointA);
  88800. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88801. this._dragPlane.lookAt(this._lookAt);
  88802. }
  88803. else {
  88804. this._dragPlane.position.copyFrom(this._pointA);
  88805. this._dragPlane.lookAt(ray.origin);
  88806. }
  88807. this._dragPlane.computeWorldMatrix(true);
  88808. };
  88809. /**
  88810. * Detaches the behavior from the mesh
  88811. */
  88812. PointerDragBehavior.prototype.detach = function () {
  88813. if (this._pointerObserver) {
  88814. this._scene.onPointerObservable.remove(this._pointerObserver);
  88815. }
  88816. };
  88817. return PointerDragBehavior;
  88818. }());
  88819. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88820. })(BABYLON || (BABYLON = {}));
  88821. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88822. var BABYLON;
  88823. (function (BABYLON) {
  88824. /**
  88825. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88826. */
  88827. var MultiPointerScaleBehavior = /** @class */ (function () {
  88828. function MultiPointerScaleBehavior() {
  88829. this._startDistance = 0;
  88830. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88831. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  88832. this._sceneRenderObserver = null;
  88833. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  88834. this._dragBehaviorA.moveAttached = false;
  88835. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  88836. this._dragBehaviorB.moveAttached = false;
  88837. }
  88838. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  88839. /**
  88840. * The name of the behavior
  88841. */
  88842. get: function () {
  88843. return "MultiPointerScale";
  88844. },
  88845. enumerable: true,
  88846. configurable: true
  88847. });
  88848. /**
  88849. * Initializes the behavior
  88850. */
  88851. MultiPointerScaleBehavior.prototype.init = function () { };
  88852. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  88853. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  88854. };
  88855. /**
  88856. * Attaches the scale behavior the passed in mesh
  88857. * @param ownerNode The mesh that will be scaled around once attached
  88858. */
  88859. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  88860. var _this = this;
  88861. this._ownerNode = ownerNode;
  88862. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  88863. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  88864. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88865. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88866. _this._dragBehaviorA.releaseDrag();
  88867. }
  88868. else {
  88869. _this._initialScale.copyFrom(ownerNode.scaling);
  88870. _this._startDistance = _this._getCurrentDistance();
  88871. }
  88872. }
  88873. });
  88874. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  88875. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88876. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88877. _this._dragBehaviorB.releaseDrag();
  88878. }
  88879. else {
  88880. _this._initialScale.copyFrom(ownerNode.scaling);
  88881. _this._startDistance = _this._getCurrentDistance();
  88882. }
  88883. }
  88884. });
  88885. // Once both drag behaviors are active scale based on the distance between the two pointers
  88886. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88887. behavior.onDragObservable.add(function () {
  88888. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88889. var ratio = _this._getCurrentDistance() / _this._startDistance;
  88890. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  88891. }
  88892. });
  88893. });
  88894. ownerNode.addBehavior(this._dragBehaviorA);
  88895. ownerNode.addBehavior(this._dragBehaviorB);
  88896. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88897. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88898. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88899. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  88900. if (change.length() > 0.01) {
  88901. ownerNode.scaling.addInPlace(change);
  88902. }
  88903. }
  88904. });
  88905. };
  88906. /**
  88907. * Detaches the behavior from the mesh
  88908. */
  88909. MultiPointerScaleBehavior.prototype.detach = function () {
  88910. var _this = this;
  88911. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88912. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88913. behavior.onDragStartObservable.clear();
  88914. behavior.onDragObservable.clear();
  88915. _this._ownerNode.removeBehavior(behavior);
  88916. });
  88917. };
  88918. return MultiPointerScaleBehavior;
  88919. }());
  88920. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  88921. })(BABYLON || (BABYLON = {}));
  88922. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  88923. var BABYLON;
  88924. (function (BABYLON) {
  88925. /**
  88926. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  88927. */
  88928. var SixDofDragBehavior = /** @class */ (function () {
  88929. function SixDofDragBehavior() {
  88930. this._sceneRenderObserver = null;
  88931. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  88932. this._moving = false;
  88933. this._startingOrientation = new BABYLON.Quaternion();
  88934. /**
  88935. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 5)
  88936. */
  88937. this.zDragFactor = 5;
  88938. /**
  88939. * If the behavior is currently in a dragging state
  88940. */
  88941. this.dragging = false;
  88942. /**
  88943. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  88944. */
  88945. this.dragDeltaRatio = 0.2;
  88946. /**
  88947. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88948. */
  88949. this.currentDraggingPointerID = -1;
  88950. }
  88951. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  88952. /**
  88953. * The name of the behavior
  88954. */
  88955. get: function () {
  88956. return "SixDofDrag";
  88957. },
  88958. enumerable: true,
  88959. configurable: true
  88960. });
  88961. /**
  88962. * Initializes the behavior
  88963. */
  88964. SixDofDragBehavior.prototype.init = function () { };
  88965. /**
  88966. * Attaches the scale behavior the passed in mesh
  88967. * @param ownerNode The mesh that will be scaled around once attached
  88968. */
  88969. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  88970. var _this = this;
  88971. this._ownerNode = ownerNode;
  88972. this._scene = this._ownerNode.getScene();
  88973. if (!SixDofDragBehavior._virtualScene) {
  88974. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  88975. this._scene.getEngine().scenes.pop();
  88976. }
  88977. var pickedMesh = null;
  88978. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  88979. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  88980. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88981. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  88982. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88983. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  88984. var pickPredicate = function (m) {
  88985. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  88986. };
  88987. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88988. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88989. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88990. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  88991. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88992. // Set position and orientation of the controller
  88993. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88994. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88995. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  88996. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88997. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  88998. if (!pickedMesh.rotationQuaternion) {
  88999. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  89000. }
  89001. var oldParent = pickedMesh.parent;
  89002. pickedMesh.setParent(null);
  89003. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  89004. pickedMesh.setParent(oldParent);
  89005. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89006. // Update state
  89007. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89008. _this.dragging = true;
  89009. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  89010. }
  89011. }
  89012. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  89013. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  89014. _this.dragging = false;
  89015. _this._moving = false;
  89016. _this.currentDraggingPointerID = -1;
  89017. pickedMesh = null;
  89018. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89019. }
  89020. }
  89021. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  89022. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  89023. // Calculate controller drag distance in controller space
  89024. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  89025. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  89026. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  89027. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  89028. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  89029. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  89030. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  89031. if (_this._virtualDragMesh.position.z < 0) {
  89032. _this._virtualDragMesh.position.z = 0;
  89033. }
  89034. // Update the controller position
  89035. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  89036. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  89037. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  89038. // Move the virtualObjectsPosition into the picked mesh's space if needed
  89039. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  89040. if (pickedMesh.parent) {
  89041. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  89042. }
  89043. if (!_this._moving) {
  89044. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  89045. }
  89046. _this._moving = true;
  89047. }
  89048. }
  89049. });
  89050. var tmpQuaternion = new BABYLON.Quaternion();
  89051. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  89052. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  89053. if (_this.dragging && _this._moving && pickedMesh) {
  89054. // Slowly move mesh to avoid jitter
  89055. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  89056. // Get change in rotation
  89057. tmpQuaternion.copyFrom(_this._startingOrientation);
  89058. tmpQuaternion.x = -tmpQuaternion.x;
  89059. tmpQuaternion.y = -tmpQuaternion.y;
  89060. tmpQuaternion.z = -tmpQuaternion.z;
  89061. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  89062. // Convert change in rotation to only y axis rotation
  89063. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  89064. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  89065. // Slowly move mesh to avoid jitter
  89066. var oldParent = pickedMesh.parent;
  89067. pickedMesh.setParent(null);
  89068. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  89069. pickedMesh.setParent(oldParent);
  89070. }
  89071. });
  89072. };
  89073. /**
  89074. * Detaches the behavior from the mesh
  89075. */
  89076. SixDofDragBehavior.prototype.detach = function () {
  89077. this._scene.onPointerObservable.remove(this._pointerObserver);
  89078. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  89079. this._virtualOriginMesh.dispose();
  89080. this._virtualDragMesh.dispose();
  89081. };
  89082. return SixDofDragBehavior;
  89083. }());
  89084. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  89085. })(BABYLON || (BABYLON = {}));
  89086. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  89087. var BABYLON;
  89088. (function (BABYLON) {
  89089. /**
  89090. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  89091. */
  89092. var Gizmo = /** @class */ (function () {
  89093. /**
  89094. * Creates a gizmo
  89095. * @param gizmoLayer The utility layer the gizmo will be added to
  89096. */
  89097. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  89098. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89099. var _this = this;
  89100. this.gizmoLayer = gizmoLayer;
  89101. this._scaleFactor = 3;
  89102. /**
  89103. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  89104. */
  89105. this.updateGizmoRotationToMatchAttachedMesh = true;
  89106. /**
  89107. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  89108. */
  89109. this.updateGizmoPositionToMatchAttachedMesh = true;
  89110. /**
  89111. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  89112. */
  89113. this._updateScale = true;
  89114. this._interactionsEnabled = true;
  89115. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89116. var tempVector = new BABYLON.Vector3();
  89117. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89118. if (_this.attachedMesh) {
  89119. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89120. if (!_this._rootMesh.rotationQuaternion) {
  89121. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  89122. }
  89123. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  89124. }
  89125. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89126. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89127. }
  89128. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89129. _this._rootMesh.position.subtractToRef(_this.gizmoLayer.utilityLayerScene.activeCamera.position, tempVector);
  89130. var dist = tempVector.length() / _this._scaleFactor;
  89131. _this._rootMesh.scaling.set(dist, dist, dist);
  89132. }
  89133. }
  89134. });
  89135. this.attachedMesh = null;
  89136. }
  89137. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89138. /**
  89139. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89140. * * When set, interactions will be enabled
  89141. */
  89142. get: function () {
  89143. return this._attachedMesh;
  89144. },
  89145. set: function (value) {
  89146. this._attachedMesh = value;
  89147. this._rootMesh.setEnabled(value ? true : false);
  89148. this._attachedMeshChanged(value);
  89149. },
  89150. enumerable: true,
  89151. configurable: true
  89152. });
  89153. Gizmo.prototype._attachedMeshChanged = function (value) {
  89154. };
  89155. /**
  89156. * Disposes of the gizmo
  89157. */
  89158. Gizmo.prototype.dispose = function () {
  89159. this._rootMesh.dispose();
  89160. if (this._beforeRenderObserver) {
  89161. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89162. }
  89163. };
  89164. return Gizmo;
  89165. }());
  89166. BABYLON.Gizmo = Gizmo;
  89167. })(BABYLON || (BABYLON = {}));
  89168. //# sourceMappingURL=babylon.gizmo.js.map
  89169. var BABYLON;
  89170. (function (BABYLON) {
  89171. /**
  89172. * Single axis drag gizmo
  89173. */
  89174. var AxisDragGizmo = /** @class */ (function (_super) {
  89175. __extends(AxisDragGizmo, _super);
  89176. /**
  89177. * Creates an AxisDragGizmo
  89178. * @param gizmoLayer The utility layer the gizmo will be added to
  89179. * @param dragAxis The axis which the gizmo will be able to drag on
  89180. * @param color The color of the gizmo
  89181. */
  89182. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89183. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89184. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89185. var _this = _super.call(this, gizmoLayer) || this;
  89186. _this._pointerObserver = null;
  89187. /**
  89188. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89189. */
  89190. _this.snapDistance = 0;
  89191. /**
  89192. * Event that fires each time the gizmo snaps to a new location.
  89193. * * snapDistance is the the change in distance
  89194. */
  89195. _this.onSnapObservable = new BABYLON.Observable();
  89196. // Create Material
  89197. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89198. coloredMaterial.disableLighting = true;
  89199. coloredMaterial.emissiveColor = color;
  89200. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89201. hoverMaterial.disableLighting = true;
  89202. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89203. // Build mesh on root node
  89204. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89205. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89206. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89207. arrow.addChild(arrowMesh);
  89208. arrow.addChild(arrowTail);
  89209. // Position arrow pointing in its drag axis
  89210. arrowMesh.scaling.scaleInPlace(0.05);
  89211. arrowMesh.material = coloredMaterial;
  89212. arrowMesh.rotation.x = Math.PI / 2;
  89213. arrowMesh.position.z += 0.3;
  89214. arrowTail.rotation.x = Math.PI / 2;
  89215. arrowTail.material = coloredMaterial;
  89216. arrowTail.position.z += 0.15;
  89217. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89218. _this._rootMesh.addChild(arrow);
  89219. var currentSnapDragDistance = 0;
  89220. var tmpVector = new BABYLON.Vector3();
  89221. var tmpSnapEvent = { snapDistance: 0 };
  89222. // Add drag behavior to handle events when the gizmo is dragged
  89223. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89224. _this.dragBehavior.moveAttached = false;
  89225. _this._rootMesh.addBehavior(_this.dragBehavior);
  89226. _this.dragBehavior.onDragObservable.add(function (event) {
  89227. if (_this.attachedMesh) {
  89228. // Snapping logic
  89229. if (_this.snapDistance == 0) {
  89230. _this.attachedMesh.position.addInPlace(event.delta);
  89231. }
  89232. else {
  89233. currentSnapDragDistance += event.dragDistance;
  89234. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89235. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89236. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89237. event.delta.normalizeToRef(tmpVector);
  89238. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89239. _this.attachedMesh.position.addInPlace(tmpVector);
  89240. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89241. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89242. }
  89243. }
  89244. }
  89245. });
  89246. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89247. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89248. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89249. m.material = hoverMaterial;
  89250. });
  89251. }
  89252. else {
  89253. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89254. m.material = coloredMaterial;
  89255. });
  89256. }
  89257. });
  89258. return _this;
  89259. }
  89260. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89261. if (this.dragBehavior) {
  89262. this.dragBehavior.enabled = value ? true : false;
  89263. }
  89264. };
  89265. /**
  89266. * Disposes of the gizmo
  89267. */
  89268. AxisDragGizmo.prototype.dispose = function () {
  89269. this.onSnapObservable.clear();
  89270. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89271. this.dragBehavior.detach();
  89272. _super.prototype.dispose.call(this);
  89273. };
  89274. return AxisDragGizmo;
  89275. }(BABYLON.Gizmo));
  89276. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89277. })(BABYLON || (BABYLON = {}));
  89278. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89279. var BABYLON;
  89280. (function (BABYLON) {
  89281. /**
  89282. * Single axis scale gizmo
  89283. */
  89284. var AxisScaleGizmo = /** @class */ (function (_super) {
  89285. __extends(AxisScaleGizmo, _super);
  89286. /**
  89287. * Creates an AxisScaleGizmo
  89288. * @param gizmoLayer The utility layer the gizmo will be added to
  89289. * @param dragAxis The axis which the gizmo will be able to scale on
  89290. * @param color The color of the gizmo
  89291. */
  89292. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89293. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89294. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89295. var _this = _super.call(this, gizmoLayer) || this;
  89296. _this._pointerObserver = null;
  89297. /**
  89298. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89299. */
  89300. _this.snapDistance = 0;
  89301. /**
  89302. * Event that fires each time the gizmo snaps to a new location.
  89303. * * snapDistance is the the change in distance
  89304. */
  89305. _this.onSnapObservable = new BABYLON.Observable();
  89306. // Create Material
  89307. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89308. coloredMaterial.disableLighting = true;
  89309. coloredMaterial.emissiveColor = color;
  89310. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89311. hoverMaterial.disableLighting = true;
  89312. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89313. // Build mesh on root node
  89314. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89315. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89316. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89317. arrow.addChild(arrowMesh);
  89318. arrow.addChild(arrowTail);
  89319. // Position arrow pointing in its drag axis
  89320. arrowMesh.scaling.scaleInPlace(0.1);
  89321. arrowMesh.material = coloredMaterial;
  89322. arrowMesh.rotation.x = Math.PI / 2;
  89323. arrowMesh.position.z += 0.3;
  89324. arrowTail.rotation.x = Math.PI / 2;
  89325. arrowTail.material = coloredMaterial;
  89326. arrowTail.position.z += 0.15;
  89327. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89328. _this._rootMesh.addChild(arrow);
  89329. // Add drag behavior to handle events when the gizmo is dragged
  89330. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89331. _this.dragBehavior.moveAttached = false;
  89332. _this._rootMesh.addBehavior(_this.dragBehavior);
  89333. var currentSnapDragDistance = 0;
  89334. var tmpVector = new BABYLON.Vector3();
  89335. var tmpSnapEvent = { snapDistance: 0 };
  89336. _this.dragBehavior.onDragObservable.add(function (event) {
  89337. if (_this.attachedMesh) {
  89338. // Snapping logic
  89339. var snapped = false;
  89340. var dragSteps = 0;
  89341. if (_this.snapDistance == 0) {
  89342. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89343. }
  89344. else {
  89345. currentSnapDragDistance += event.dragDistance;
  89346. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89347. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89348. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89349. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89350. snapped = true;
  89351. }
  89352. else {
  89353. tmpVector.scaleInPlace(0);
  89354. }
  89355. }
  89356. var invertCount = 0;
  89357. if (_this.attachedMesh.scaling["x"] < 0) {
  89358. invertCount++;
  89359. }
  89360. if (_this.attachedMesh.scaling["y"] < 0) {
  89361. invertCount++;
  89362. }
  89363. if (_this.attachedMesh.scaling["z"] < 0) {
  89364. invertCount++;
  89365. }
  89366. if (invertCount % 2 == 0) {
  89367. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89368. }
  89369. else {
  89370. _this.attachedMesh.scaling.subtractInPlace(tmpVector);
  89371. }
  89372. if (snapped) {
  89373. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89374. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89375. }
  89376. }
  89377. });
  89378. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89379. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89380. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89381. m.material = hoverMaterial;
  89382. });
  89383. }
  89384. else {
  89385. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89386. m.material = coloredMaterial;
  89387. });
  89388. }
  89389. });
  89390. return _this;
  89391. }
  89392. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89393. if (this.dragBehavior) {
  89394. this.dragBehavior.enabled = value ? true : false;
  89395. }
  89396. };
  89397. /**
  89398. * Disposes of the gizmo
  89399. */
  89400. AxisScaleGizmo.prototype.dispose = function () {
  89401. this.onSnapObservable.clear();
  89402. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89403. this.dragBehavior.detach();
  89404. _super.prototype.dispose.call(this);
  89405. };
  89406. return AxisScaleGizmo;
  89407. }(BABYLON.Gizmo));
  89408. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89409. })(BABYLON || (BABYLON = {}));
  89410. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89411. var BABYLON;
  89412. (function (BABYLON) {
  89413. /**
  89414. * Single plane rotation gizmo
  89415. */
  89416. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89417. __extends(PlaneRotationGizmo, _super);
  89418. /**
  89419. * Creates a PlaneRotationGizmo
  89420. * @param gizmoLayer The utility layer the gizmo will be added to
  89421. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89422. * @param color The color of the gizmo
  89423. */
  89424. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89425. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89426. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89427. var _this = _super.call(this, gizmoLayer) || this;
  89428. _this._pointerObserver = null;
  89429. /**
  89430. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89431. */
  89432. _this.snapDistance = 0;
  89433. /**
  89434. * Event that fires each time the gizmo snaps to a new location.
  89435. * * snapDistance is the the change in distance
  89436. */
  89437. _this.onSnapObservable = new BABYLON.Observable();
  89438. // Create Material
  89439. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89440. coloredMaterial.disableLighting = true;
  89441. coloredMaterial.emissiveColor = color;
  89442. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89443. hoverMaterial.disableLighting = true;
  89444. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89445. // Build mesh on root node
  89446. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89447. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89448. // Position arrow pointing in its drag axis
  89449. rotationMesh.scaling.scaleInPlace(0.1);
  89450. rotationMesh.material = coloredMaterial;
  89451. rotationMesh.rotation.x = Math.PI / 2;
  89452. parentMesh.addChild(rotationMesh);
  89453. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89454. _this._rootMesh.addChild(parentMesh);
  89455. // Add drag behavior to handle events when the gizmo is dragged
  89456. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89457. _this.dragBehavior.moveAttached = false;
  89458. _this._rootMesh.addBehavior(_this.dragBehavior);
  89459. var lastDragPosition = null;
  89460. _this.dragBehavior.onDragStartObservable.add(function (e) {
  89461. if (_this.attachedMesh) {
  89462. lastDragPosition = e.dragPlanePoint;
  89463. }
  89464. });
  89465. var rotationMatrix = new BABYLON.Matrix();
  89466. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89467. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89468. var tmpSnapEvent = { snapDistance: 0 };
  89469. var currentSnapDragDistance = 0;
  89470. _this.dragBehavior.onDragObservable.add(function (event) {
  89471. if (_this.attachedMesh && lastDragPosition) {
  89472. if (!_this.attachedMesh.rotationQuaternion) {
  89473. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  89474. }
  89475. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89476. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89477. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89478. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89479. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89480. var angle = Math.atan2(cross.length(), dot);
  89481. planeNormalTowardsCamera.copyFrom(planeNormal);
  89482. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89483. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89484. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89485. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89486. }
  89487. // Flip up vector depending on which side the camera is on
  89488. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89489. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89490. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89491. planeNormalTowardsCamera.scaleInPlace(-1);
  89492. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89493. }
  89494. }
  89495. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89496. if (halfCircleSide)
  89497. angle = -angle;
  89498. // Snapping logic
  89499. var snapped = false;
  89500. if (_this.snapDistance != 0) {
  89501. currentSnapDragDistance += angle;
  89502. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89503. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89504. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89505. angle = _this.snapDistance * dragSteps;
  89506. snapped = true;
  89507. }
  89508. else {
  89509. angle = 0;
  89510. }
  89511. }
  89512. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89513. var quaternionCoefficient = Math.sin(angle / 2);
  89514. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89515. // Rotate selected mesh quaternion over fixed axis
  89516. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89517. lastDragPosition = event.dragPlanePoint;
  89518. if (snapped) {
  89519. tmpSnapEvent.snapDistance = angle;
  89520. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89521. }
  89522. }
  89523. });
  89524. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89525. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89526. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89527. m.material = hoverMaterial;
  89528. });
  89529. }
  89530. else {
  89531. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89532. m.material = coloredMaterial;
  89533. });
  89534. }
  89535. });
  89536. return _this;
  89537. }
  89538. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89539. if (this.dragBehavior) {
  89540. this.dragBehavior.enabled = value ? true : false;
  89541. }
  89542. };
  89543. /**
  89544. * Disposes of the gizmo
  89545. */
  89546. PlaneRotationGizmo.prototype.dispose = function () {
  89547. this.onSnapObservable.clear();
  89548. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89549. this.dragBehavior.detach();
  89550. _super.prototype.dispose.call(this);
  89551. };
  89552. return PlaneRotationGizmo;
  89553. }(BABYLON.Gizmo));
  89554. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89555. })(BABYLON || (BABYLON = {}));
  89556. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89557. var BABYLON;
  89558. (function (BABYLON) {
  89559. /**
  89560. * Gizmo that enables dragging a mesh along 3 axis
  89561. */
  89562. var PositionGizmo = /** @class */ (function (_super) {
  89563. __extends(PositionGizmo, _super);
  89564. /**
  89565. * Creates a PositionGizmo
  89566. * @param gizmoLayer The utility layer the gizmo will be added to
  89567. */
  89568. function PositionGizmo(gizmoLayer) {
  89569. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89570. var _this = _super.call(this, gizmoLayer) || this;
  89571. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89572. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89573. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89574. _this.attachedMesh = null;
  89575. return _this;
  89576. }
  89577. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89578. set: function (mesh) {
  89579. if (this.xGizmo) {
  89580. this.xGizmo.attachedMesh = mesh;
  89581. this.yGizmo.attachedMesh = mesh;
  89582. this.zGizmo.attachedMesh = mesh;
  89583. }
  89584. },
  89585. enumerable: true,
  89586. configurable: true
  89587. });
  89588. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89589. get: function () {
  89590. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89591. },
  89592. set: function (value) {
  89593. if (this.xGizmo) {
  89594. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89595. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89596. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89597. }
  89598. },
  89599. enumerable: true,
  89600. configurable: true
  89601. });
  89602. /**
  89603. * Disposes of the gizmo
  89604. */
  89605. PositionGizmo.prototype.dispose = function () {
  89606. this.xGizmo.dispose();
  89607. this.yGizmo.dispose();
  89608. this.zGizmo.dispose();
  89609. };
  89610. return PositionGizmo;
  89611. }(BABYLON.Gizmo));
  89612. BABYLON.PositionGizmo = PositionGizmo;
  89613. })(BABYLON || (BABYLON = {}));
  89614. //# sourceMappingURL=babylon.positionGizmo.js.map
  89615. var BABYLON;
  89616. (function (BABYLON) {
  89617. /**
  89618. * Gizmo that enables rotating a mesh along 3 axis
  89619. */
  89620. var RotationGizmo = /** @class */ (function (_super) {
  89621. __extends(RotationGizmo, _super);
  89622. /**
  89623. * Creates a RotationGizmo
  89624. * @param gizmoLayer The utility layer the gizmo will be added to
  89625. */
  89626. function RotationGizmo(gizmoLayer) {
  89627. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89628. var _this = _super.call(this, gizmoLayer) || this;
  89629. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89630. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89631. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89632. _this.attachedMesh = null;
  89633. return _this;
  89634. }
  89635. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  89636. set: function (mesh) {
  89637. if (this.xGizmo) {
  89638. this.xGizmo.attachedMesh = mesh;
  89639. this.yGizmo.attachedMesh = mesh;
  89640. this.zGizmo.attachedMesh = mesh;
  89641. }
  89642. },
  89643. enumerable: true,
  89644. configurable: true
  89645. });
  89646. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89647. get: function () {
  89648. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89649. },
  89650. set: function (value) {
  89651. if (this.xGizmo) {
  89652. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89653. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89654. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89655. }
  89656. },
  89657. enumerable: true,
  89658. configurable: true
  89659. });
  89660. /**
  89661. * Disposes of the gizmo
  89662. */
  89663. RotationGizmo.prototype.dispose = function () {
  89664. this.xGizmo.dispose();
  89665. this.yGizmo.dispose();
  89666. this.zGizmo.dispose();
  89667. };
  89668. return RotationGizmo;
  89669. }(BABYLON.Gizmo));
  89670. BABYLON.RotationGizmo = RotationGizmo;
  89671. })(BABYLON || (BABYLON = {}));
  89672. //# sourceMappingURL=babylon.rotationGizmo.js.map
  89673. var BABYLON;
  89674. (function (BABYLON) {
  89675. /**
  89676. * Gizmo that enables scaling a mesh along 3 axis
  89677. */
  89678. var ScaleGizmo = /** @class */ (function (_super) {
  89679. __extends(ScaleGizmo, _super);
  89680. /**
  89681. * Creates a ScaleGizmo
  89682. * @param gizmoLayer The utility layer the gizmo will be added to
  89683. */
  89684. function ScaleGizmo(gizmoLayer) {
  89685. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89686. var _this = _super.call(this, gizmoLayer) || this;
  89687. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89688. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89689. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89690. _this.attachedMesh = null;
  89691. return _this;
  89692. }
  89693. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  89694. set: function (mesh) {
  89695. if (this.xGizmo) {
  89696. this.xGizmo.attachedMesh = mesh;
  89697. this.yGizmo.attachedMesh = mesh;
  89698. this.zGizmo.attachedMesh = mesh;
  89699. }
  89700. },
  89701. enumerable: true,
  89702. configurable: true
  89703. });
  89704. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89705. get: function () {
  89706. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  89707. },
  89708. set: function (value) {
  89709. if (this.xGizmo) {
  89710. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89711. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89712. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  89713. }
  89714. },
  89715. enumerable: true,
  89716. configurable: true
  89717. });
  89718. /**
  89719. * Disposes of the gizmo
  89720. */
  89721. ScaleGizmo.prototype.dispose = function () {
  89722. this.xGizmo.dispose();
  89723. this.yGizmo.dispose();
  89724. this.zGizmo.dispose();
  89725. };
  89726. return ScaleGizmo;
  89727. }(BABYLON.Gizmo));
  89728. BABYLON.ScaleGizmo = ScaleGizmo;
  89729. })(BABYLON || (BABYLON = {}));
  89730. //# sourceMappingURL=babylon.scaleGizmo.js.map
  89731. var BABYLON;
  89732. (function (BABYLON) {
  89733. /**
  89734. * Bounding box gizmo
  89735. */
  89736. var BoundingBoxGizmo = /** @class */ (function (_super) {
  89737. __extends(BoundingBoxGizmo, _super);
  89738. /**
  89739. * Creates an BoundingBoxGizmo
  89740. * @param gizmoLayer The utility layer the gizmo will be added to
  89741. * @param color The color of the gizmo
  89742. */
  89743. function BoundingBoxGizmo(color, gizmoLayer) {
  89744. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89745. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89746. var _this = _super.call(this, gizmoLayer) || this;
  89747. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  89748. _this._renderObserver = null;
  89749. _this._pointerObserver = null;
  89750. _this._scaleDragSpeed = 0.2;
  89751. _this._tmpQuaternion = new BABYLON.Quaternion();
  89752. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89753. /**
  89754. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  89755. */
  89756. _this.rotationSphereSize = 0.1;
  89757. /**
  89758. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  89759. */
  89760. _this.scaleBoxSize = 0.1;
  89761. /**
  89762. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  89763. */
  89764. _this.fixedDragMeshScreenSize = false;
  89765. /**
  89766. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  89767. */
  89768. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  89769. /**
  89770. * Fired when a rotation sphere or scale box is dragged
  89771. */
  89772. _this.onDragStartObservable = new BABYLON.Observable();
  89773. /**
  89774. * Fired when a rotation sphere or scale box drag is started
  89775. */
  89776. _this.onDragObservable = new BABYLON.Observable();
  89777. /**
  89778. * Fired when a rotation sphere or scale box drag is needed
  89779. */
  89780. _this.onDragEndObservable = new BABYLON.Observable();
  89781. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  89782. _this._updateScale = false;
  89783. // Create Materials
  89784. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89785. coloredMaterial.disableLighting = true;
  89786. coloredMaterial.emissiveColor = color;
  89787. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89788. hoverColoredMaterial.disableLighting = true;
  89789. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89790. // Build bounding box out of lines
  89791. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89792. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  89793. var lines = [];
  89794. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  89795. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89796. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89797. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89798. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89799. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89800. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89801. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89802. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89803. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89804. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89805. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89806. lines.forEach(function (l) {
  89807. l.color = color;
  89808. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  89809. l.isPickable = false;
  89810. _this._lineBoundingBox.addChild(l);
  89811. });
  89812. _this._rootMesh.addChild(_this._lineBoundingBox);
  89813. // Create rotation spheres
  89814. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89815. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  89816. var _loop_1 = function (i_1) {
  89817. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  89818. sphere.rotationQuaternion = new BABYLON.Quaternion();
  89819. sphere.material = coloredMaterial;
  89820. // Drag behavior
  89821. _dragBehavior = new BABYLON.PointerDragBehavior({});
  89822. _dragBehavior.moveAttached = false;
  89823. _dragBehavior.updateDragPlane = false;
  89824. sphere.addBehavior(_dragBehavior);
  89825. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  89826. var totalTurnAmountOfDrag = 0;
  89827. _dragBehavior.onDragStartObservable.add(function (event) {
  89828. startingTurnDirection.copyFrom(sphere.forward);
  89829. totalTurnAmountOfDrag = 0;
  89830. });
  89831. _dragBehavior.onDragObservable.add(function (event) {
  89832. _this.onDragObservable.notifyObservers({});
  89833. if (_this.attachedMesh) {
  89834. var worldDragDirection = startingTurnDirection;
  89835. // Project the world right on to the drag plane
  89836. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  89837. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  89838. // project drag delta on to the resulting drag axis and rotate based on that
  89839. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  89840. // Rotate based on axis
  89841. if (!_this.attachedMesh.rotationQuaternion) {
  89842. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89843. }
  89844. // Do not allow the object to turn more than a full circle
  89845. totalTurnAmountOfDrag += projectDist;
  89846. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  89847. if (i_1 >= 8) {
  89848. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  89849. }
  89850. else if (i_1 >= 4) {
  89851. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  89852. }
  89853. else {
  89854. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  89855. }
  89856. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  89857. }
  89858. }
  89859. });
  89860. // Selection/deselection
  89861. _dragBehavior.onDragStartObservable.add(function () {
  89862. _this.onDragStartObservable.notifyObservers({});
  89863. _this._selectNode(sphere);
  89864. });
  89865. _dragBehavior.onDragEndObservable.add(function () {
  89866. _this.onDragEndObservable.notifyObservers({});
  89867. _this._selectNode(null);
  89868. });
  89869. this_1._rotateSpheresParent.addChild(sphere);
  89870. };
  89871. var this_1 = this, _dragBehavior;
  89872. for (var i_1 = 0; i_1 < 12; i_1++) {
  89873. _loop_1(i_1);
  89874. }
  89875. _this._rootMesh.addChild(_this._rotateSpheresParent);
  89876. // Create scale cubes
  89877. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89878. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  89879. for (var i = 0; i < 2; i++) {
  89880. for (var j = 0; j < 2; j++) {
  89881. var _loop_2 = function () {
  89882. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  89883. box.material = coloredMaterial;
  89884. // Dragging logic
  89885. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  89886. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89887. _dragBehavior.moveAttached = false;
  89888. box.addBehavior(_dragBehavior);
  89889. _dragBehavior.onDragObservable.add(function (event) {
  89890. _this.onDragObservable.notifyObservers({});
  89891. if (_this.attachedMesh) {
  89892. // Current boudning box dimensions
  89893. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  89894. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  89895. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  89896. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  89897. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  89898. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  89899. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  89900. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  89901. // Update scale and position
  89902. _this.attachedMesh.scaling.addInPlace(deltaScale);
  89903. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  89904. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  89905. }
  89906. });
  89907. // Selection/deselection
  89908. _dragBehavior.onDragStartObservable.add(function () {
  89909. _this.onDragStartObservable.notifyObservers({});
  89910. _this._selectNode(box);
  89911. });
  89912. _dragBehavior.onDragEndObservable.add(function () {
  89913. _this.onDragEndObservable.notifyObservers({});
  89914. _this._selectNode(null);
  89915. });
  89916. this_2._scaleBoxesParent.addChild(box);
  89917. };
  89918. var this_2 = this, _dragBehavior;
  89919. for (var k = 0; k < 2; k++) {
  89920. _loop_2();
  89921. }
  89922. }
  89923. }
  89924. _this._rootMesh.addChild(_this._scaleBoxesParent);
  89925. // Hover color change
  89926. var pointerIds = new Array();
  89927. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89928. if (!pointerIds[pointerInfo.event.pointerId]) {
  89929. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  89930. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  89931. pointerIds[pointerInfo.event.pointerId] = mesh;
  89932. mesh.material = hoverColoredMaterial;
  89933. }
  89934. });
  89935. }
  89936. else {
  89937. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  89938. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  89939. delete pointerIds[pointerInfo.event.pointerId];
  89940. }
  89941. }
  89942. });
  89943. // Update bounding box positions
  89944. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  89945. _this._updateBoundingBox();
  89946. });
  89947. _this._updateBoundingBox();
  89948. return _this;
  89949. }
  89950. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  89951. this._rotateSpheresParent.getChildMeshes()
  89952. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  89953. m.isVisible = (!selectedMesh || m == selectedMesh);
  89954. });
  89955. };
  89956. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  89957. if (this.attachedMesh) {
  89958. // Update bounding dimensions/positions
  89959. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  89960. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  89961. this._boundingDimensions.copyFrom(boundBoxDimensions);
  89962. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  89963. }
  89964. // Update rotation sphere locations
  89965. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  89966. for (var i = 0; i < 3; i++) {
  89967. for (var j = 0; j < 2; j++) {
  89968. for (var k = 0; k < 2; k++) {
  89969. var index = ((i * 4) + (j * 2)) + k;
  89970. if (i == 0) {
  89971. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89972. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89973. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89974. }
  89975. if (i == 1) {
  89976. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  89977. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89978. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89979. }
  89980. if (i == 2) {
  89981. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  89982. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89983. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89984. }
  89985. if (this.fixedDragMeshScreenSize) {
  89986. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  89987. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  89988. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  89989. }
  89990. else {
  89991. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  89992. }
  89993. }
  89994. }
  89995. }
  89996. // Update scale box locations
  89997. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  89998. for (var i = 0; i < 2; i++) {
  89999. for (var j = 0; j < 2; j++) {
  90000. for (var k = 0; k < 2; k++) {
  90001. var index = ((i * 4) + (j * 2)) + k;
  90002. if (scaleBoxes[index]) {
  90003. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  90004. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  90005. if (this.fixedDragMeshScreenSize) {
  90006. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  90007. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  90008. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  90009. }
  90010. else {
  90011. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  90012. }
  90013. }
  90014. }
  90015. }
  90016. }
  90017. };
  90018. /**
  90019. * Enables rotation on the specified axis and disables rotation on the others
  90020. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  90021. */
  90022. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  90023. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  90024. if (i < 4) {
  90025. m.setEnabled(axis.indexOf("x") != -1);
  90026. }
  90027. else if (i < 8) {
  90028. m.setEnabled(axis.indexOf("y") != -1);
  90029. }
  90030. else {
  90031. m.setEnabled(axis.indexOf("z") != -1);
  90032. }
  90033. });
  90034. };
  90035. /**
  90036. * Disposes of the gizmo
  90037. */
  90038. BoundingBoxGizmo.prototype.dispose = function () {
  90039. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  90040. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  90041. this._lineBoundingBox.dispose();
  90042. this._rotateSpheresParent.dispose();
  90043. this._scaleBoxesParent.dispose();
  90044. _super.prototype.dispose.call(this);
  90045. };
  90046. return BoundingBoxGizmo;
  90047. }(BABYLON.Gizmo));
  90048. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  90049. })(BABYLON || (BABYLON = {}));
  90050. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  90051. var BABYLON;
  90052. (function (BABYLON) {
  90053. /**
  90054. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  90055. */
  90056. var GizmoManager = /** @class */ (function () {
  90057. /**
  90058. * Instatiates a gizmo manager
  90059. * @param scene the scene to overlay the gizmos on top of
  90060. * @param options If only a single gizmo should exist at one time
  90061. */
  90062. function GizmoManager(scene, options) {
  90063. var _this = this;
  90064. this.scene = scene;
  90065. // Set of gizmos that are currently in the scene for each mesh
  90066. this._gizmoSet = {};
  90067. this._pointerObserver = null;
  90068. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  90069. // Options parsing
  90070. if (!options) {
  90071. options = {};
  90072. }
  90073. if (options.singleGizmo === undefined) {
  90074. options.singleGizmo = true;
  90075. }
  90076. // Instatiate/dispose gizmos based on pointer actions
  90077. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  90078. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  90079. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  90080. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  90081. if (options.singleGizmo) {
  90082. _this._clearGizmos();
  90083. }
  90084. // Enable gizmo when mesh is selected
  90085. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  90086. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90087. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  90088. }
  90089. else {
  90090. if (!options.singleGizmo) {
  90091. // Disable gizmo when clicked again
  90092. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  90093. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  90094. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  90095. }
  90096. }
  90097. }
  90098. else {
  90099. if (options.singleGizmo) {
  90100. // Disable gizmo when clicked away
  90101. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  90102. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  90103. if (gizmoPick && !gizmoPick.hit) {
  90104. _this._clearGizmos();
  90105. }
  90106. }
  90107. }
  90108. }
  90109. }
  90110. });
  90111. }
  90112. /**
  90113. * Disposes of the gizmo manager
  90114. */
  90115. GizmoManager.prototype.dispose = function () {
  90116. this.scene.onPointerObservable.remove(this._pointerObserver);
  90117. this._clearGizmos();
  90118. this._gizmoLayer.dispose();
  90119. };
  90120. GizmoManager.prototype._clearGizmos = function () {
  90121. for (var key in this._gizmoSet) {
  90122. if (this._gizmoSet.hasOwnProperty(key)) {
  90123. this._gizmoSet[key].positionGizmo.dispose();
  90124. this._gizmoSet[key].rotationGizmo.dispose();
  90125. delete this._gizmoSet[key];
  90126. }
  90127. }
  90128. };
  90129. return GizmoManager;
  90130. }());
  90131. BABYLON.GizmoManager = GizmoManager;
  90132. })(BABYLON || (BABYLON = {}));
  90133. //# sourceMappingURL=babylon.gizmoManager.js.map
  90134. var BABYLON;
  90135. (function (BABYLON) {
  90136. /**
  90137. * Defines a target to use with MorphTargetManager
  90138. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90139. */
  90140. var MorphTarget = /** @class */ (function () {
  90141. /**
  90142. * Creates a new MorphTarget
  90143. * @param name defines the name of the target
  90144. * @param influence defines the influence to use
  90145. */
  90146. function MorphTarget(
  90147. /** defines the name of the target */
  90148. name, influence, scene) {
  90149. if (influence === void 0) { influence = 0; }
  90150. if (scene === void 0) { scene = null; }
  90151. this.name = name;
  90152. /**
  90153. * Gets or sets the list of animations
  90154. */
  90155. this.animations = new Array();
  90156. this._positions = null;
  90157. this._normals = null;
  90158. this._tangents = null;
  90159. /**
  90160. * Observable raised when the influence changes
  90161. */
  90162. this.onInfluenceChanged = new BABYLON.Observable();
  90163. this._animationPropertiesOverride = null;
  90164. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90165. this.influence = influence;
  90166. }
  90167. Object.defineProperty(MorphTarget.prototype, "influence", {
  90168. /**
  90169. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90170. */
  90171. get: function () {
  90172. return this._influence;
  90173. },
  90174. set: function (influence) {
  90175. if (this._influence === influence) {
  90176. return;
  90177. }
  90178. var previous = this._influence;
  90179. this._influence = influence;
  90180. if (this.onInfluenceChanged.hasObservers) {
  90181. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90182. }
  90183. },
  90184. enumerable: true,
  90185. configurable: true
  90186. });
  90187. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90188. /**
  90189. * Gets or sets the animation properties override
  90190. */
  90191. get: function () {
  90192. if (!this._animationPropertiesOverride && this._scene) {
  90193. return this._scene.animationPropertiesOverride;
  90194. }
  90195. return this._animationPropertiesOverride;
  90196. },
  90197. set: function (value) {
  90198. this._animationPropertiesOverride = value;
  90199. },
  90200. enumerable: true,
  90201. configurable: true
  90202. });
  90203. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90204. /**
  90205. * Gets a boolean defining if the target contains position data
  90206. */
  90207. get: function () {
  90208. return !!this._positions;
  90209. },
  90210. enumerable: true,
  90211. configurable: true
  90212. });
  90213. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90214. /**
  90215. * Gets a boolean defining if the target contains normal data
  90216. */
  90217. get: function () {
  90218. return !!this._normals;
  90219. },
  90220. enumerable: true,
  90221. configurable: true
  90222. });
  90223. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90224. /**
  90225. * Gets a boolean defining if the target contains tangent data
  90226. */
  90227. get: function () {
  90228. return !!this._tangents;
  90229. },
  90230. enumerable: true,
  90231. configurable: true
  90232. });
  90233. /**
  90234. * Affects position data to this target
  90235. * @param data defines the position data to use
  90236. */
  90237. MorphTarget.prototype.setPositions = function (data) {
  90238. this._positions = data;
  90239. };
  90240. /**
  90241. * Gets the position data stored in this target
  90242. * @returns a FloatArray containing the position data (or null if not present)
  90243. */
  90244. MorphTarget.prototype.getPositions = function () {
  90245. return this._positions;
  90246. };
  90247. /**
  90248. * Affects normal data to this target
  90249. * @param data defines the normal data to use
  90250. */
  90251. MorphTarget.prototype.setNormals = function (data) {
  90252. this._normals = data;
  90253. };
  90254. /**
  90255. * Gets the normal data stored in this target
  90256. * @returns a FloatArray containing the normal data (or null if not present)
  90257. */
  90258. MorphTarget.prototype.getNormals = function () {
  90259. return this._normals;
  90260. };
  90261. /**
  90262. * Affects tangent data to this target
  90263. * @param data defines the tangent data to use
  90264. */
  90265. MorphTarget.prototype.setTangents = function (data) {
  90266. this._tangents = data;
  90267. };
  90268. /**
  90269. * Gets the tangent data stored in this target
  90270. * @returns a FloatArray containing the tangent data (or null if not present)
  90271. */
  90272. MorphTarget.prototype.getTangents = function () {
  90273. return this._tangents;
  90274. };
  90275. /**
  90276. * Serializes the current target into a Serialization object
  90277. * @returns the serialized object
  90278. */
  90279. MorphTarget.prototype.serialize = function () {
  90280. var serializationObject = {};
  90281. serializationObject.name = this.name;
  90282. serializationObject.influence = this.influence;
  90283. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90284. if (this.hasNormals) {
  90285. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90286. }
  90287. if (this.hasTangents) {
  90288. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90289. }
  90290. // Animations
  90291. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90292. return serializationObject;
  90293. };
  90294. // Statics
  90295. /**
  90296. * Creates a new target from serialized data
  90297. * @param serializationObject defines the serialized data to use
  90298. * @returns a new MorphTarget
  90299. */
  90300. MorphTarget.Parse = function (serializationObject) {
  90301. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90302. result.setPositions(serializationObject.positions);
  90303. if (serializationObject.normals) {
  90304. result.setNormals(serializationObject.normals);
  90305. }
  90306. if (serializationObject.tangents) {
  90307. result.setTangents(serializationObject.tangents);
  90308. }
  90309. // Animations
  90310. if (serializationObject.animations) {
  90311. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90312. var parsedAnimation = serializationObject.animations[animationIndex];
  90313. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90314. }
  90315. }
  90316. return result;
  90317. };
  90318. /**
  90319. * Creates a MorphTarget from mesh data
  90320. * @param mesh defines the source mesh
  90321. * @param name defines the name to use for the new target
  90322. * @param influence defines the influence to attach to the target
  90323. * @returns a new MorphTarget
  90324. */
  90325. MorphTarget.FromMesh = function (mesh, name, influence) {
  90326. if (!name) {
  90327. name = mesh.name;
  90328. }
  90329. var result = new MorphTarget(name, influence, mesh.getScene());
  90330. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90331. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90332. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90333. }
  90334. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90335. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90336. }
  90337. return result;
  90338. };
  90339. return MorphTarget;
  90340. }());
  90341. BABYLON.MorphTarget = MorphTarget;
  90342. })(BABYLON || (BABYLON = {}));
  90343. //# sourceMappingURL=babylon.morphTarget.js.map
  90344. var BABYLON;
  90345. (function (BABYLON) {
  90346. /**
  90347. * This class is used to deform meshes using morphing between different targets
  90348. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90349. */
  90350. var MorphTargetManager = /** @class */ (function () {
  90351. /**
  90352. * Creates a new MorphTargetManager
  90353. * @param scene defines the current scene
  90354. */
  90355. function MorphTargetManager(scene) {
  90356. if (scene === void 0) { scene = null; }
  90357. this._targets = new Array();
  90358. this._targetObservable = new Array();
  90359. this._activeTargets = new BABYLON.SmartArray(16);
  90360. this._supportsNormals = false;
  90361. this._supportsTangents = false;
  90362. this._vertexCount = 0;
  90363. this._uniqueId = 0;
  90364. this._tempInfluences = new Array();
  90365. if (!scene) {
  90366. scene = BABYLON.Engine.LastCreatedScene;
  90367. }
  90368. this._scene = scene;
  90369. if (this._scene) {
  90370. this._scene.morphTargetManagers.push(this);
  90371. this._uniqueId = this._scene.getUniqueId();
  90372. }
  90373. }
  90374. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90375. /**
  90376. * Gets the unique ID of this manager
  90377. */
  90378. get: function () {
  90379. return this._uniqueId;
  90380. },
  90381. enumerable: true,
  90382. configurable: true
  90383. });
  90384. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90385. /**
  90386. * Gets the number of vertices handled by this manager
  90387. */
  90388. get: function () {
  90389. return this._vertexCount;
  90390. },
  90391. enumerable: true,
  90392. configurable: true
  90393. });
  90394. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  90395. /**
  90396. * Gets a boolean indicating if this manager supports morphing of normals
  90397. */
  90398. get: function () {
  90399. return this._supportsNormals;
  90400. },
  90401. enumerable: true,
  90402. configurable: true
  90403. });
  90404. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  90405. /**
  90406. * Gets a boolean indicating if this manager supports morphing of tangents
  90407. */
  90408. get: function () {
  90409. return this._supportsTangents;
  90410. },
  90411. enumerable: true,
  90412. configurable: true
  90413. });
  90414. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  90415. /**
  90416. * Gets the number of targets stored in this manager
  90417. */
  90418. get: function () {
  90419. return this._targets.length;
  90420. },
  90421. enumerable: true,
  90422. configurable: true
  90423. });
  90424. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  90425. /**
  90426. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90427. */
  90428. get: function () {
  90429. return this._activeTargets.length;
  90430. },
  90431. enumerable: true,
  90432. configurable: true
  90433. });
  90434. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90435. /**
  90436. * Gets the list of influences (one per target)
  90437. */
  90438. get: function () {
  90439. return this._influences;
  90440. },
  90441. enumerable: true,
  90442. configurable: true
  90443. });
  90444. /**
  90445. * Gets the active target at specified index. An active target is a target with an influence > 0
  90446. * @param index defines the index to check
  90447. * @returns the requested target
  90448. */
  90449. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90450. return this._activeTargets.data[index];
  90451. };
  90452. /**
  90453. * Gets the target at specified index
  90454. * @param index defines the index to check
  90455. * @returns the requested target
  90456. */
  90457. MorphTargetManager.prototype.getTarget = function (index) {
  90458. return this._targets[index];
  90459. };
  90460. /**
  90461. * Add a new target to this manager
  90462. * @param target defines the target to add
  90463. */
  90464. MorphTargetManager.prototype.addTarget = function (target) {
  90465. var _this = this;
  90466. this._targets.push(target);
  90467. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90468. _this._syncActiveTargets(needUpdate);
  90469. }));
  90470. this._syncActiveTargets(true);
  90471. };
  90472. /**
  90473. * Removes a target from the manager
  90474. * @param target defines the target to remove
  90475. */
  90476. MorphTargetManager.prototype.removeTarget = function (target) {
  90477. var index = this._targets.indexOf(target);
  90478. if (index >= 0) {
  90479. this._targets.splice(index, 1);
  90480. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90481. this._syncActiveTargets(true);
  90482. }
  90483. };
  90484. /**
  90485. * Serializes the current manager into a Serialization object
  90486. * @returns the serialized object
  90487. */
  90488. MorphTargetManager.prototype.serialize = function () {
  90489. var serializationObject = {};
  90490. serializationObject.id = this.uniqueId;
  90491. serializationObject.targets = [];
  90492. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90493. var target = _a[_i];
  90494. serializationObject.targets.push(target.serialize());
  90495. }
  90496. return serializationObject;
  90497. };
  90498. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90499. var influenceCount = 0;
  90500. this._activeTargets.reset();
  90501. this._supportsNormals = true;
  90502. this._supportsTangents = true;
  90503. this._vertexCount = 0;
  90504. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90505. var target = _a[_i];
  90506. this._activeTargets.push(target);
  90507. this._tempInfluences[influenceCount++] = target.influence;
  90508. var positions = target.getPositions();
  90509. if (positions) {
  90510. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90511. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90512. var vertexCount = positions.length / 3;
  90513. if (this._vertexCount === 0) {
  90514. this._vertexCount = vertexCount;
  90515. }
  90516. else if (this._vertexCount !== vertexCount) {
  90517. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90518. return;
  90519. }
  90520. }
  90521. }
  90522. if (!this._influences || this._influences.length !== influenceCount) {
  90523. this._influences = new Float32Array(influenceCount);
  90524. }
  90525. for (var index = 0; index < influenceCount; index++) {
  90526. this._influences[index] = this._tempInfluences[index];
  90527. }
  90528. if (needUpdate) {
  90529. this.synchronize();
  90530. }
  90531. };
  90532. /**
  90533. * Syncrhonize the targets with all the meshes using this morph target manager
  90534. */
  90535. MorphTargetManager.prototype.synchronize = function () {
  90536. if (!this._scene) {
  90537. return;
  90538. }
  90539. // Flag meshes as dirty to resync with the active targets
  90540. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90541. var mesh = _a[_i];
  90542. if (mesh.morphTargetManager === this) {
  90543. mesh._syncGeometryWithMorphTargetManager();
  90544. }
  90545. }
  90546. };
  90547. // Statics
  90548. /**
  90549. * Creates a new MorphTargetManager from serialized data
  90550. * @param serializationObject defines the serialized data
  90551. * @param scene defines the hosting scene
  90552. * @returns the new MorphTargetManager
  90553. */
  90554. MorphTargetManager.Parse = function (serializationObject, scene) {
  90555. var result = new MorphTargetManager(scene);
  90556. result._uniqueId = serializationObject.id;
  90557. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90558. var targetData = _a[_i];
  90559. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90560. }
  90561. return result;
  90562. };
  90563. return MorphTargetManager;
  90564. }());
  90565. BABYLON.MorphTargetManager = MorphTargetManager;
  90566. })(BABYLON || (BABYLON = {}));
  90567. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90568. var BABYLON;
  90569. (function (BABYLON) {
  90570. var Octree = /** @class */ (function () {
  90571. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90572. if (maxDepth === void 0) { maxDepth = 2; }
  90573. this.maxDepth = maxDepth;
  90574. this.dynamicContent = new Array();
  90575. this._maxBlockCapacity = maxBlockCapacity || 64;
  90576. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90577. this._creationFunc = creationFunc;
  90578. }
  90579. // Methods
  90580. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90581. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90582. };
  90583. Octree.prototype.addMesh = function (entry) {
  90584. for (var index = 0; index < this.blocks.length; index++) {
  90585. var block = this.blocks[index];
  90586. block.addEntry(entry);
  90587. }
  90588. };
  90589. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  90590. this._selectionContent.reset();
  90591. for (var index = 0; index < this.blocks.length; index++) {
  90592. var block = this.blocks[index];
  90593. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  90594. }
  90595. if (allowDuplicate) {
  90596. this._selectionContent.concat(this.dynamicContent);
  90597. }
  90598. else {
  90599. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90600. }
  90601. return this._selectionContent;
  90602. };
  90603. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  90604. this._selectionContent.reset();
  90605. for (var index = 0; index < this.blocks.length; index++) {
  90606. var block = this.blocks[index];
  90607. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  90608. }
  90609. if (allowDuplicate) {
  90610. this._selectionContent.concat(this.dynamicContent);
  90611. }
  90612. else {
  90613. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90614. }
  90615. return this._selectionContent;
  90616. };
  90617. Octree.prototype.intersectsRay = function (ray) {
  90618. this._selectionContent.reset();
  90619. for (var index = 0; index < this.blocks.length; index++) {
  90620. var block = this.blocks[index];
  90621. block.intersectsRay(ray, this._selectionContent);
  90622. }
  90623. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90624. return this._selectionContent;
  90625. };
  90626. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  90627. target.blocks = new Array();
  90628. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  90629. // Segmenting space
  90630. for (var x = 0; x < 2; x++) {
  90631. for (var y = 0; y < 2; y++) {
  90632. for (var z = 0; z < 2; z++) {
  90633. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  90634. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  90635. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  90636. block.addEntries(entries);
  90637. target.blocks.push(block);
  90638. }
  90639. }
  90640. }
  90641. };
  90642. Octree.CreationFuncForMeshes = function (entry, block) {
  90643. var boundingInfo = entry.getBoundingInfo();
  90644. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90645. block.entries.push(entry);
  90646. }
  90647. };
  90648. Octree.CreationFuncForSubMeshes = function (entry, block) {
  90649. var boundingInfo = entry.getBoundingInfo();
  90650. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90651. block.entries.push(entry);
  90652. }
  90653. };
  90654. return Octree;
  90655. }());
  90656. BABYLON.Octree = Octree;
  90657. })(BABYLON || (BABYLON = {}));
  90658. //# sourceMappingURL=babylon.octree.js.map
  90659. var BABYLON;
  90660. (function (BABYLON) {
  90661. var OctreeBlock = /** @class */ (function () {
  90662. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  90663. this.entries = new Array();
  90664. this._boundingVectors = new Array();
  90665. this._capacity = capacity;
  90666. this._depth = depth;
  90667. this._maxDepth = maxDepth;
  90668. this._creationFunc = creationFunc;
  90669. this._minPoint = minPoint;
  90670. this._maxPoint = maxPoint;
  90671. this._boundingVectors.push(minPoint.clone());
  90672. this._boundingVectors.push(maxPoint.clone());
  90673. this._boundingVectors.push(minPoint.clone());
  90674. this._boundingVectors[2].x = maxPoint.x;
  90675. this._boundingVectors.push(minPoint.clone());
  90676. this._boundingVectors[3].y = maxPoint.y;
  90677. this._boundingVectors.push(minPoint.clone());
  90678. this._boundingVectors[4].z = maxPoint.z;
  90679. this._boundingVectors.push(maxPoint.clone());
  90680. this._boundingVectors[5].z = minPoint.z;
  90681. this._boundingVectors.push(maxPoint.clone());
  90682. this._boundingVectors[6].x = minPoint.x;
  90683. this._boundingVectors.push(maxPoint.clone());
  90684. this._boundingVectors[7].y = minPoint.y;
  90685. }
  90686. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  90687. // Property
  90688. get: function () {
  90689. return this._capacity;
  90690. },
  90691. enumerable: true,
  90692. configurable: true
  90693. });
  90694. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  90695. get: function () {
  90696. return this._minPoint;
  90697. },
  90698. enumerable: true,
  90699. configurable: true
  90700. });
  90701. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  90702. get: function () {
  90703. return this._maxPoint;
  90704. },
  90705. enumerable: true,
  90706. configurable: true
  90707. });
  90708. // Methods
  90709. OctreeBlock.prototype.addEntry = function (entry) {
  90710. if (this.blocks) {
  90711. for (var index = 0; index < this.blocks.length; index++) {
  90712. var block = this.blocks[index];
  90713. block.addEntry(entry);
  90714. }
  90715. return;
  90716. }
  90717. this._creationFunc(entry, this);
  90718. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  90719. this.createInnerBlocks();
  90720. }
  90721. };
  90722. OctreeBlock.prototype.addEntries = function (entries) {
  90723. for (var index = 0; index < entries.length; index++) {
  90724. var mesh = entries[index];
  90725. this.addEntry(mesh);
  90726. }
  90727. };
  90728. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  90729. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  90730. if (this.blocks) {
  90731. for (var index = 0; index < this.blocks.length; index++) {
  90732. var block = this.blocks[index];
  90733. block.select(frustumPlanes, selection, allowDuplicate);
  90734. }
  90735. return;
  90736. }
  90737. if (allowDuplicate) {
  90738. selection.concat(this.entries);
  90739. }
  90740. else {
  90741. selection.concatWithNoDuplicate(this.entries);
  90742. }
  90743. }
  90744. };
  90745. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  90746. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  90747. if (this.blocks) {
  90748. for (var index = 0; index < this.blocks.length; index++) {
  90749. var block = this.blocks[index];
  90750. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  90751. }
  90752. return;
  90753. }
  90754. if (allowDuplicate) {
  90755. selection.concat(this.entries);
  90756. }
  90757. else {
  90758. selection.concatWithNoDuplicate(this.entries);
  90759. }
  90760. }
  90761. };
  90762. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  90763. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  90764. if (this.blocks) {
  90765. for (var index = 0; index < this.blocks.length; index++) {
  90766. var block = this.blocks[index];
  90767. block.intersectsRay(ray, selection);
  90768. }
  90769. return;
  90770. }
  90771. selection.concatWithNoDuplicate(this.entries);
  90772. }
  90773. };
  90774. OctreeBlock.prototype.createInnerBlocks = function () {
  90775. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  90776. };
  90777. return OctreeBlock;
  90778. }());
  90779. BABYLON.OctreeBlock = OctreeBlock;
  90780. })(BABYLON || (BABYLON = {}));
  90781. //# sourceMappingURL=babylon.octreeBlock.js.map
  90782. var BABYLON;
  90783. (function (BABYLON) {
  90784. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  90785. __extends(VRDistortionCorrectionPostProcess, _super);
  90786. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  90787. var _this = _super.call(this, name, "vrDistortionCorrection", [
  90788. 'LensCenter',
  90789. 'Scale',
  90790. 'ScaleIn',
  90791. 'HmdWarpParam'
  90792. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  90793. _this._isRightEye = isRightEye;
  90794. _this._distortionFactors = vrMetrics.distortionK;
  90795. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  90796. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  90797. _this.adaptScaleToCurrentViewport = true;
  90798. _this.onSizeChangedObservable.add(function () {
  90799. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  90800. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  90801. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  90802. });
  90803. _this.onApplyObservable.add(function (effect) {
  90804. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  90805. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  90806. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  90807. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  90808. });
  90809. return _this;
  90810. }
  90811. return VRDistortionCorrectionPostProcess;
  90812. }(BABYLON.PostProcess));
  90813. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  90814. })(BABYLON || (BABYLON = {}));
  90815. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  90816. var BABYLON;
  90817. (function (BABYLON) {
  90818. /**
  90819. * Postprocess used to generate anaglyphic rendering
  90820. */
  90821. var AnaglyphPostProcess = /** @class */ (function (_super) {
  90822. __extends(AnaglyphPostProcess, _super);
  90823. /**
  90824. * Creates a new AnaglyphPostProcess
  90825. * @param name defines postprocess name
  90826. * @param options defines creation options or target ratio scale
  90827. * @param rigCameras defines cameras using this postprocess
  90828. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  90829. * @param engine defines hosting engine
  90830. * @param reusable defines if the postprocess will be reused multiple times per frame
  90831. */
  90832. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  90833. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  90834. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90835. _this.onApplyObservable.add(function (effect) {
  90836. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  90837. });
  90838. return _this;
  90839. }
  90840. return AnaglyphPostProcess;
  90841. }(BABYLON.PostProcess));
  90842. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  90843. })(BABYLON || (BABYLON = {}));
  90844. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  90845. var BABYLON;
  90846. (function (BABYLON) {
  90847. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  90848. __extends(StereoscopicInterlacePostProcess, _super);
  90849. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  90850. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  90851. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90852. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90853. _this.onSizeChangedObservable.add(function () {
  90854. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90855. });
  90856. _this.onApplyObservable.add(function (effect) {
  90857. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  90858. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  90859. });
  90860. return _this;
  90861. }
  90862. return StereoscopicInterlacePostProcess;
  90863. }(BABYLON.PostProcess));
  90864. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  90865. })(BABYLON || (BABYLON = {}));
  90866. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  90867. var BABYLON;
  90868. (function (BABYLON) {
  90869. /**
  90870. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  90871. * Screen rotation is taken into account.
  90872. */
  90873. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  90874. function FreeCameraDeviceOrientationInput() {
  90875. var _this = this;
  90876. this._screenOrientationAngle = 0;
  90877. this._screenQuaternion = new BABYLON.Quaternion();
  90878. this._alpha = 0;
  90879. this._beta = 0;
  90880. this._gamma = 0;
  90881. this._orientationChanged = function () {
  90882. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  90883. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  90884. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  90885. };
  90886. this._deviceOrientation = function (evt) {
  90887. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  90888. _this._beta = evt.beta !== null ? evt.beta : 0;
  90889. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  90890. };
  90891. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  90892. this._orientationChanged();
  90893. }
  90894. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  90895. get: function () {
  90896. return this._camera;
  90897. },
  90898. set: function (camera) {
  90899. this._camera = camera;
  90900. if (this._camera != null && !this._camera.rotationQuaternion) {
  90901. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  90902. }
  90903. },
  90904. enumerable: true,
  90905. configurable: true
  90906. });
  90907. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90908. window.addEventListener("orientationchange", this._orientationChanged);
  90909. window.addEventListener("deviceorientation", this._deviceOrientation);
  90910. //In certain cases, the attach control is called AFTER orientation was changed,
  90911. //So this is needed.
  90912. this._orientationChanged();
  90913. };
  90914. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  90915. window.removeEventListener("orientationchange", this._orientationChanged);
  90916. window.removeEventListener("deviceorientation", this._deviceOrientation);
  90917. };
  90918. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  90919. //if no device orientation provided, don't update the rotation.
  90920. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  90921. if (!this._alpha)
  90922. return;
  90923. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  90924. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  90925. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  90926. //Mirror on XY Plane
  90927. this._camera.rotationQuaternion.z *= -1;
  90928. this._camera.rotationQuaternion.w *= -1;
  90929. };
  90930. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  90931. return "FreeCameraDeviceOrientationInput";
  90932. };
  90933. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  90934. return "deviceOrientation";
  90935. };
  90936. return FreeCameraDeviceOrientationInput;
  90937. }());
  90938. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  90939. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  90940. })(BABYLON || (BABYLON = {}));
  90941. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  90942. var BABYLON;
  90943. (function (BABYLON) {
  90944. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  90945. function ArcRotateCameraVRDeviceOrientationInput() {
  90946. this.alphaCorrection = 1;
  90947. this.betaCorrection = 1;
  90948. this.gammaCorrection = 1;
  90949. this._alpha = 0;
  90950. this._gamma = 0;
  90951. this._dirty = false;
  90952. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  90953. }
  90954. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90955. this.camera.attachControl(element, noPreventDefault);
  90956. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  90957. };
  90958. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  90959. if (evt.alpha !== null) {
  90960. this._alpha = +evt.alpha | 0;
  90961. }
  90962. if (evt.gamma !== null) {
  90963. this._gamma = +evt.gamma | 0;
  90964. }
  90965. this._dirty = true;
  90966. };
  90967. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  90968. if (this._dirty) {
  90969. this._dirty = false;
  90970. if (this._gamma < 0) {
  90971. this._gamma = 180 + this._gamma;
  90972. }
  90973. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  90974. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  90975. }
  90976. };
  90977. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  90978. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  90979. };
  90980. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  90981. return "ArcRotateCameraVRDeviceOrientationInput";
  90982. };
  90983. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  90984. return "VRDeviceOrientation";
  90985. };
  90986. return ArcRotateCameraVRDeviceOrientationInput;
  90987. }());
  90988. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  90989. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  90990. })(BABYLON || (BABYLON = {}));
  90991. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  90992. var BABYLON;
  90993. (function (BABYLON) {
  90994. var VRCameraMetrics = /** @class */ (function () {
  90995. function VRCameraMetrics() {
  90996. this.compensateDistortion = true;
  90997. }
  90998. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  90999. get: function () {
  91000. return this.hResolution / (2 * this.vResolution);
  91001. },
  91002. enumerable: true,
  91003. configurable: true
  91004. });
  91005. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  91006. get: function () {
  91007. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  91008. },
  91009. enumerable: true,
  91010. configurable: true
  91011. });
  91012. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  91013. get: function () {
  91014. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91015. var h = (4 * meters) / this.hScreenSize;
  91016. return BABYLON.Matrix.Translation(h, 0, 0);
  91017. },
  91018. enumerable: true,
  91019. configurable: true
  91020. });
  91021. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  91022. get: function () {
  91023. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  91024. var h = (4 * meters) / this.hScreenSize;
  91025. return BABYLON.Matrix.Translation(-h, 0, 0);
  91026. },
  91027. enumerable: true,
  91028. configurable: true
  91029. });
  91030. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  91031. get: function () {
  91032. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  91033. },
  91034. enumerable: true,
  91035. configurable: true
  91036. });
  91037. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  91038. get: function () {
  91039. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  91040. },
  91041. enumerable: true,
  91042. configurable: true
  91043. });
  91044. VRCameraMetrics.GetDefault = function () {
  91045. var result = new VRCameraMetrics();
  91046. result.hResolution = 1280;
  91047. result.vResolution = 800;
  91048. result.hScreenSize = 0.149759993;
  91049. result.vScreenSize = 0.0935999975;
  91050. result.vScreenCenter = 0.0467999987;
  91051. result.eyeToScreenDistance = 0.0410000011;
  91052. result.lensSeparationDistance = 0.0635000020;
  91053. result.interpupillaryDistance = 0.0640000030;
  91054. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  91055. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  91056. result.postProcessScaleFactor = 1.714605507808412;
  91057. result.lensCenterOffset = 0.151976421;
  91058. return result;
  91059. };
  91060. return VRCameraMetrics;
  91061. }());
  91062. BABYLON.VRCameraMetrics = VRCameraMetrics;
  91063. })(BABYLON || (BABYLON = {}));
  91064. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  91065. var BABYLON;
  91066. (function (BABYLON) {
  91067. /**
  91068. * This represents a WebVR camera.
  91069. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  91070. * @example http://doc.babylonjs.com/how_to/webvr_camera
  91071. */
  91072. var WebVRFreeCamera = /** @class */ (function (_super) {
  91073. __extends(WebVRFreeCamera, _super);
  91074. /**
  91075. * Instantiates a WebVRFreeCamera.
  91076. * @param name The name of the WebVRFreeCamera
  91077. * @param position The starting anchor position for the camera
  91078. * @param scene The scene the camera belongs to
  91079. * @param webVROptions a set of customizable options for the webVRCamera
  91080. */
  91081. function WebVRFreeCamera(name, position, scene, webVROptions) {
  91082. if (webVROptions === void 0) { webVROptions = {}; }
  91083. var _this = _super.call(this, name, position, scene) || this;
  91084. _this.webVROptions = webVROptions;
  91085. /**
  91086. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  91087. */
  91088. _this._vrDevice = null;
  91089. /**
  91090. * The rawPose of the vrDevice.
  91091. */
  91092. _this.rawPose = null;
  91093. _this._specsVersion = "1.1";
  91094. _this._attached = false;
  91095. _this._descendants = [];
  91096. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  91097. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  91098. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  91099. _this._standingMatrix = null;
  91100. /**
  91101. * Represents device position in babylon space.
  91102. */
  91103. _this.devicePosition = BABYLON.Vector3.Zero();
  91104. /**
  91105. * Represents device rotation in babylon space.
  91106. */
  91107. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  91108. /**
  91109. * The scale of the device to be used when translating from device space to babylon space.
  91110. */
  91111. _this.deviceScaleFactor = 1;
  91112. _this._deviceToWorld = BABYLON.Matrix.Identity();
  91113. _this._worldToDevice = BABYLON.Matrix.Identity();
  91114. /**
  91115. * References to the webVR controllers for the vrDevice.
  91116. */
  91117. _this.controllers = [];
  91118. /**
  91119. * Emits an event when a controller is attached.
  91120. */
  91121. _this.onControllersAttachedObservable = new BABYLON.Observable();
  91122. /**
  91123. * Emits an event when a controller's mesh has been loaded;
  91124. */
  91125. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91126. /**
  91127. * If the rig cameras be used as parent instead of this camera.
  91128. */
  91129. _this.rigParenting = true;
  91130. _this._defaultHeight = undefined;
  91131. _this._workingVector = BABYLON.Vector3.Zero();
  91132. _this._oneVector = BABYLON.Vector3.One();
  91133. _this._workingMatrix = BABYLON.Matrix.Identity();
  91134. _this._cache.position = BABYLON.Vector3.Zero();
  91135. if (webVROptions.defaultHeight) {
  91136. _this._defaultHeight = webVROptions.defaultHeight;
  91137. _this.position.y = _this._defaultHeight;
  91138. }
  91139. _this.minZ = 0.1;
  91140. //legacy support - the compensation boolean was removed.
  91141. if (arguments.length === 5) {
  91142. _this.webVROptions = arguments[4];
  91143. }
  91144. // default webVR options
  91145. if (_this.webVROptions.trackPosition == undefined) {
  91146. _this.webVROptions.trackPosition = true;
  91147. }
  91148. if (_this.webVROptions.controllerMeshes == undefined) {
  91149. _this.webVROptions.controllerMeshes = true;
  91150. }
  91151. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  91152. _this.webVROptions.defaultLightingOnControllers = true;
  91153. }
  91154. _this.rotationQuaternion = new BABYLON.Quaternion();
  91155. if (_this.webVROptions && _this.webVROptions.positionScale) {
  91156. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  91157. }
  91158. //enable VR
  91159. var engine = _this.getEngine();
  91160. _this._onVREnabled = function (success) { if (success) {
  91161. _this.initControllers();
  91162. } };
  91163. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  91164. engine.initWebVR().add(function (event) {
  91165. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  91166. return;
  91167. }
  91168. _this._vrDevice = event.vrDisplay;
  91169. //reset the rig parameters.
  91170. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  91171. if (_this._attached) {
  91172. _this.getEngine().enableVR();
  91173. }
  91174. });
  91175. if (typeof (VRFrameData) !== "undefined")
  91176. _this._frameData = new VRFrameData();
  91177. /**
  91178. * The idea behind the following lines:
  91179. * objects that have the camera as parent should actually have the rig cameras as a parent.
  91180. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  91181. * the second will not show it correctly.
  91182. *
  91183. * To solve this - each object that has the camera as parent will be added to a protected array.
  91184. * When the rig camera renders, it will take this array and set all of those to be its children.
  91185. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  91186. * Amazing!
  91187. */
  91188. scene.onBeforeCameraRenderObservable.add(function (camera) {
  91189. if (camera.parent === _this && _this.rigParenting) {
  91190. _this._descendants = _this.getDescendants(true, function (n) {
  91191. // don't take the cameras or the controllers!
  91192. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  91193. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  91194. return !isController && !isRigCamera;
  91195. });
  91196. _this._descendants.forEach(function (node) {
  91197. node.parent = camera;
  91198. });
  91199. }
  91200. });
  91201. scene.onAfterCameraRenderObservable.add(function (camera) {
  91202. if (camera.parent === _this && _this.rigParenting) {
  91203. _this._descendants.forEach(function (node) {
  91204. node.parent = _this;
  91205. });
  91206. }
  91207. });
  91208. return _this;
  91209. }
  91210. /**
  91211. * Gets the device distance from the ground in meters.
  91212. * @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.
  91213. */
  91214. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  91215. if (this._standingMatrix) {
  91216. // Add standing matrix offset to get real offset from ground in room
  91217. this._standingMatrix.getTranslationToRef(this._workingVector);
  91218. return this._deviceRoomPosition.y + this._workingVector.y;
  91219. }
  91220. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  91221. return this._defaultHeight || 0;
  91222. };
  91223. /**
  91224. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91225. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  91226. */
  91227. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  91228. var _this = this;
  91229. if (callback === void 0) { callback = function (bool) { }; }
  91230. // Use standing matrix if available
  91231. this.getEngine().initWebVRAsync().then(function (result) {
  91232. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  91233. callback(false);
  91234. }
  91235. else {
  91236. _this._standingMatrix = new BABYLON.Matrix();
  91237. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  91238. if (!_this.getScene().useRightHandedSystem) {
  91239. [2, 6, 8, 9, 14].forEach(function (num) {
  91240. if (_this._standingMatrix) {
  91241. _this._standingMatrix.m[num] *= -1;
  91242. }
  91243. });
  91244. }
  91245. callback(true);
  91246. }
  91247. });
  91248. };
  91249. /**
  91250. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91251. * @returns A promise with a boolean set to if the standing matrix is supported.
  91252. */
  91253. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  91254. var _this = this;
  91255. return new Promise(function (res, rej) {
  91256. _this.useStandingMatrix(function (supported) {
  91257. res(supported);
  91258. });
  91259. });
  91260. };
  91261. /**
  91262. * Disposes the camera
  91263. */
  91264. WebVRFreeCamera.prototype.dispose = function () {
  91265. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  91266. _super.prototype.dispose.call(this);
  91267. };
  91268. /**
  91269. * Gets a vrController by name.
  91270. * @param name The name of the controller to retreive
  91271. * @returns the controller matching the name specified or null if not found
  91272. */
  91273. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  91274. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  91275. var gp = _a[_i];
  91276. if (gp.hand === name) {
  91277. return gp;
  91278. }
  91279. }
  91280. return null;
  91281. };
  91282. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  91283. /**
  91284. * The controller corrisponding to the users left hand.
  91285. */
  91286. get: function () {
  91287. if (!this._leftController) {
  91288. this._leftController = this.getControllerByName("left");
  91289. }
  91290. return this._leftController;
  91291. },
  91292. enumerable: true,
  91293. configurable: true
  91294. });
  91295. ;
  91296. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  91297. /**
  91298. * The controller corrisponding to the users right hand.
  91299. */
  91300. get: function () {
  91301. if (!this._rightController) {
  91302. this._rightController = this.getControllerByName("right");
  91303. }
  91304. return this._rightController;
  91305. },
  91306. enumerable: true,
  91307. configurable: true
  91308. });
  91309. ;
  91310. /**
  91311. * Casts a ray forward from the vrCamera's gaze.
  91312. * @param length Length of the ray (default: 100)
  91313. * @returns the ray corrisponding to the gaze
  91314. */
  91315. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  91316. if (length === void 0) { length = 100; }
  91317. if (this.leftCamera) {
  91318. // Use left eye to avoid computation to compute center on every call
  91319. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  91320. }
  91321. else {
  91322. return _super.prototype.getForwardRay.call(this, length);
  91323. }
  91324. };
  91325. /**
  91326. * Updates the camera based on device's frame data
  91327. */
  91328. WebVRFreeCamera.prototype._checkInputs = function () {
  91329. if (this._vrDevice && this._vrDevice.isPresenting) {
  91330. this._vrDevice.getFrameData(this._frameData);
  91331. this.updateFromDevice(this._frameData.pose);
  91332. }
  91333. _super.prototype._checkInputs.call(this);
  91334. };
  91335. /**
  91336. * Updates the poseControlled values based on the input device pose.
  91337. * @param poseData Pose coming from the device
  91338. */
  91339. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  91340. if (poseData && poseData.orientation) {
  91341. this.rawPose = poseData;
  91342. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  91343. if (this.getScene().useRightHandedSystem) {
  91344. this._deviceRoomRotationQuaternion.z *= -1;
  91345. this._deviceRoomRotationQuaternion.w *= -1;
  91346. }
  91347. if (this.webVROptions.trackPosition && this.rawPose.position) {
  91348. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  91349. if (this.getScene().useRightHandedSystem) {
  91350. this._deviceRoomPosition.z *= -1;
  91351. }
  91352. }
  91353. }
  91354. };
  91355. /**
  91356. * WebVR's attach control will start broadcasting frames to the device.
  91357. * Note that in certain browsers (chrome for example) this function must be called
  91358. * within a user-interaction callback. Example:
  91359. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  91360. *
  91361. * @param element html element to attach the vrDevice to
  91362. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  91363. */
  91364. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  91365. _super.prototype.attachControl.call(this, element, noPreventDefault);
  91366. this._attached = true;
  91367. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  91368. if (this._vrDevice) {
  91369. this.getEngine().enableVR();
  91370. }
  91371. };
  91372. /**
  91373. * Detaches the camera from the html element and disables VR
  91374. *
  91375. * @param element html element to detach from
  91376. */
  91377. WebVRFreeCamera.prototype.detachControl = function (element) {
  91378. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  91379. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  91380. _super.prototype.detachControl.call(this, element);
  91381. this._attached = false;
  91382. this.getEngine().disableVR();
  91383. };
  91384. /**
  91385. * @returns the name of this class
  91386. */
  91387. WebVRFreeCamera.prototype.getClassName = function () {
  91388. return "WebVRFreeCamera";
  91389. };
  91390. /**
  91391. * Calls resetPose on the vrDisplay
  91392. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  91393. */
  91394. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  91395. //uses the vrDisplay's "resetPose()".
  91396. //pitch and roll won't be affected.
  91397. this._vrDevice.resetPose();
  91398. };
  91399. /**
  91400. * Updates the rig cameras (left and right eye)
  91401. */
  91402. WebVRFreeCamera.prototype._updateRigCameras = function () {
  91403. var camLeft = this._rigCameras[0];
  91404. var camRight = this._rigCameras[1];
  91405. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91406. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91407. camLeft.position.copyFrom(this._deviceRoomPosition);
  91408. camRight.position.copyFrom(this._deviceRoomPosition);
  91409. };
  91410. /**
  91411. * Updates the cached values of the camera
  91412. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  91413. */
  91414. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  91415. var _this = this;
  91416. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  91417. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  91418. if (!this.updateCacheCalled) {
  91419. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  91420. this.updateCacheCalled = true;
  91421. this.update();
  91422. }
  91423. // Set working vector to the device position in room space rotated by the new rotation
  91424. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  91425. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  91426. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  91427. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  91428. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  91429. // Add translation from anchor position
  91430. this._deviceToWorld.getTranslationToRef(this._workingVector);
  91431. this._workingVector.addInPlace(this.position);
  91432. this._workingVector.subtractInPlace(this._cache.position);
  91433. this._deviceToWorld.setTranslation(this._workingVector);
  91434. // Set an inverted matrix to be used when updating the camera
  91435. this._deviceToWorld.invertToRef(this._worldToDevice);
  91436. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  91437. this.controllers.forEach(function (controller) {
  91438. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  91439. controller.update();
  91440. });
  91441. }
  91442. if (!ignoreParentClass) {
  91443. _super.prototype._updateCache.call(this);
  91444. }
  91445. this.updateCacheCalled = false;
  91446. };
  91447. /**
  91448. * Updates the current device position and rotation in the babylon world
  91449. */
  91450. WebVRFreeCamera.prototype.update = function () {
  91451. // Get current device position in babylon world
  91452. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  91453. // Get current device rotation in babylon world
  91454. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  91455. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  91456. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  91457. _super.prototype.update.call(this);
  91458. };
  91459. /**
  91460. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  91461. * @returns an identity matrix
  91462. */
  91463. WebVRFreeCamera.prototype._getViewMatrix = function () {
  91464. return BABYLON.Matrix.Identity();
  91465. };
  91466. /**
  91467. * This function is called by the two RIG cameras.
  91468. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  91469. */
  91470. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  91471. var _this = this;
  91472. // Update the parent camera prior to using a child camera to avoid desynchronization
  91473. var parentCamera = this._cameraRigParams["parentCamera"];
  91474. parentCamera._updateCache();
  91475. //WebVR 1.1
  91476. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  91477. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  91478. if (!this.getScene().useRightHandedSystem) {
  91479. [2, 6, 8, 9, 14].forEach(function (num) {
  91480. _this._webvrViewMatrix.m[num] *= -1;
  91481. });
  91482. }
  91483. // update the camera rotation matrix
  91484. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  91485. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  91486. // Computing target and final matrix
  91487. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  91488. // should the view matrix be updated with scale and position offset?
  91489. if (parentCamera.deviceScaleFactor !== 1) {
  91490. this._webvrViewMatrix.invert();
  91491. // scale the position, if set
  91492. if (parentCamera.deviceScaleFactor) {
  91493. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  91494. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  91495. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  91496. }
  91497. this._webvrViewMatrix.invert();
  91498. }
  91499. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  91500. // Compute global position
  91501. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  91502. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  91503. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  91504. this._workingMatrix.getTranslationToRef(this._globalPosition);
  91505. this._markSyncedWithParent();
  91506. return this._webvrViewMatrix;
  91507. };
  91508. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  91509. var _this = this;
  91510. var parentCamera = this.parent;
  91511. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  91512. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  91513. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  91514. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  91515. //babylon compatible matrix
  91516. if (!this.getScene().useRightHandedSystem) {
  91517. [8, 9, 10, 11].forEach(function (num) {
  91518. _this._projectionMatrix.m[num] *= -1;
  91519. });
  91520. }
  91521. return this._projectionMatrix;
  91522. };
  91523. /**
  91524. * Initializes the controllers and their meshes
  91525. */
  91526. WebVRFreeCamera.prototype.initControllers = function () {
  91527. var _this = this;
  91528. this.controllers = [];
  91529. var manager = this.getScene().gamepadManager;
  91530. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  91531. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91532. var webVrController = gamepad;
  91533. if (webVrController.defaultModel) {
  91534. webVrController.defaultModel.setEnabled(false);
  91535. }
  91536. if (webVrController.hand === "right") {
  91537. _this._rightController = null;
  91538. }
  91539. if (webVrController.hand === "left") {
  91540. _this._leftController = null;
  91541. }
  91542. var controllerIndex = _this.controllers.indexOf(webVrController);
  91543. if (controllerIndex !== -1) {
  91544. _this.controllers.splice(controllerIndex, 1);
  91545. }
  91546. }
  91547. });
  91548. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  91549. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91550. var webVrController_1 = gamepad;
  91551. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  91552. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  91553. if (_this.webVROptions.controllerMeshes) {
  91554. if (webVrController_1.defaultModel) {
  91555. webVrController_1.defaultModel.setEnabled(true);
  91556. }
  91557. else {
  91558. // Load the meshes
  91559. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  91560. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  91561. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  91562. if (_this.webVROptions.defaultLightingOnControllers) {
  91563. if (!_this._lightOnControllers) {
  91564. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  91565. }
  91566. var activateLightOnSubMeshes_1 = function (mesh, light) {
  91567. var children = mesh.getChildren();
  91568. if (children.length !== 0) {
  91569. children.forEach(function (mesh) {
  91570. light.includedOnlyMeshes.push(mesh);
  91571. activateLightOnSubMeshes_1(mesh, light);
  91572. });
  91573. }
  91574. };
  91575. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  91576. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  91577. }
  91578. });
  91579. }
  91580. }
  91581. webVrController_1.attachToPoseControlledCamera(_this);
  91582. // since this is async - sanity check. Is the controller already stored?
  91583. if (_this.controllers.indexOf(webVrController_1) === -1) {
  91584. //add to the controllers array
  91585. _this.controllers.push(webVrController_1);
  91586. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  91587. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  91588. // So we're overriding setting left & right manually to be sure
  91589. var firstViveWandDetected = false;
  91590. for (var i = 0; i < _this.controllers.length; i++) {
  91591. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91592. if (!firstViveWandDetected) {
  91593. firstViveWandDetected = true;
  91594. _this.controllers[i].hand = "left";
  91595. }
  91596. else {
  91597. _this.controllers[i].hand = "right";
  91598. }
  91599. }
  91600. }
  91601. //did we find enough controllers? Great! let the developer know.
  91602. if (_this.controllers.length >= 2) {
  91603. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  91604. }
  91605. }
  91606. }
  91607. });
  91608. };
  91609. return WebVRFreeCamera;
  91610. }(BABYLON.FreeCamera));
  91611. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  91612. })(BABYLON || (BABYLON = {}));
  91613. //# sourceMappingURL=babylon.webVRCamera.js.map
  91614. var BABYLON;
  91615. (function (BABYLON) {
  91616. // We're mainly based on the logic defined into the FreeCamera code
  91617. /**
  91618. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  91619. * being tilted forward or back and left or right.
  91620. */
  91621. var DeviceOrientationCamera = /** @class */ (function (_super) {
  91622. __extends(DeviceOrientationCamera, _super);
  91623. /**
  91624. * Creates a new device orientation camera
  91625. * @param name The name of the camera
  91626. * @param position The start position camera
  91627. * @param scene The scene the camera belongs to
  91628. */
  91629. function DeviceOrientationCamera(name, position, scene) {
  91630. var _this = _super.call(this, name, position, scene) || this;
  91631. _this._quaternionCache = new BABYLON.Quaternion();
  91632. _this.inputs.addDeviceOrientation();
  91633. return _this;
  91634. }
  91635. /**
  91636. * Gets the current instance class name ("DeviceOrientationCamera").
  91637. * This helps avoiding instanceof at run time.
  91638. * @returns the class name
  91639. */
  91640. DeviceOrientationCamera.prototype.getClassName = function () {
  91641. return "DeviceOrientationCamera";
  91642. };
  91643. /**
  91644. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  91645. */
  91646. DeviceOrientationCamera.prototype._checkInputs = function () {
  91647. _super.prototype._checkInputs.call(this);
  91648. this._quaternionCache.copyFrom(this.rotationQuaternion);
  91649. if (this._initialQuaternion) {
  91650. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91651. }
  91652. };
  91653. /**
  91654. * Reset the camera to its default orientation on the specified axis only.
  91655. * @param axis The axis to reset
  91656. */
  91657. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  91658. var _this = this;
  91659. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  91660. //can only work if this camera has a rotation quaternion already.
  91661. if (!this.rotationQuaternion)
  91662. return;
  91663. if (!this._initialQuaternion) {
  91664. this._initialQuaternion = new BABYLON.Quaternion();
  91665. }
  91666. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  91667. ['x', 'y', 'z'].forEach(function (axisName) {
  91668. if (!axis[axisName]) {
  91669. _this._initialQuaternion[axisName] = 0;
  91670. }
  91671. else {
  91672. _this._initialQuaternion[axisName] *= -1;
  91673. }
  91674. });
  91675. this._initialQuaternion.normalize();
  91676. //force rotation update
  91677. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91678. };
  91679. return DeviceOrientationCamera;
  91680. }(BABYLON.FreeCamera));
  91681. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  91682. })(BABYLON || (BABYLON = {}));
  91683. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  91684. var BABYLON;
  91685. (function (BABYLON) {
  91686. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  91687. __extends(VRDeviceOrientationFreeCamera, _super);
  91688. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91689. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91690. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91691. var _this = _super.call(this, name, position, scene) || this;
  91692. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91693. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91694. return _this;
  91695. }
  91696. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  91697. return "VRDeviceOrientationFreeCamera";
  91698. };
  91699. return VRDeviceOrientationFreeCamera;
  91700. }(BABYLON.DeviceOrientationCamera));
  91701. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  91702. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  91703. __extends(VRDeviceOrientationGamepadCamera, _super);
  91704. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91705. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91706. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91707. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  91708. _this.inputs.addGamepad();
  91709. return _this;
  91710. }
  91711. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  91712. return "VRDeviceOrientationGamepadCamera";
  91713. };
  91714. return VRDeviceOrientationGamepadCamera;
  91715. }(VRDeviceOrientationFreeCamera));
  91716. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  91717. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  91718. __extends(VRDeviceOrientationArcRotateCamera, _super);
  91719. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  91720. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91721. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91722. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91723. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91724. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91725. _this.inputs.addVRDeviceOrientation();
  91726. return _this;
  91727. }
  91728. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  91729. return "VRDeviceOrientationArcRotateCamera";
  91730. };
  91731. return VRDeviceOrientationArcRotateCamera;
  91732. }(BABYLON.ArcRotateCamera));
  91733. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  91734. })(BABYLON || (BABYLON = {}));
  91735. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  91736. var BABYLON;
  91737. (function (BABYLON) {
  91738. /**
  91739. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91740. */
  91741. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91742. __extends(AnaglyphFreeCamera, _super);
  91743. /**
  91744. * Creates a new AnaglyphFreeCamera
  91745. * @param name defines camera name
  91746. * @param position defines initial position
  91747. * @param interaxialDistance defines distance between each color axis
  91748. * @param scene defines the hosting scene
  91749. */
  91750. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91751. var _this = _super.call(this, name, position, scene) || this;
  91752. _this.interaxialDistance = interaxialDistance;
  91753. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91754. return _this;
  91755. }
  91756. /**
  91757. * Gets camera class name
  91758. * @returns AnaglyphFreeCamera
  91759. */
  91760. AnaglyphFreeCamera.prototype.getClassName = function () {
  91761. return "AnaglyphFreeCamera";
  91762. };
  91763. return AnaglyphFreeCamera;
  91764. }(BABYLON.FreeCamera));
  91765. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91766. /**
  91767. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91768. */
  91769. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91770. __extends(AnaglyphArcRotateCamera, _super);
  91771. /**
  91772. * Creates a new AnaglyphArcRotateCamera
  91773. * @param name defines camera name
  91774. * @param alpha defines alpha angle (in radians)
  91775. * @param beta defines beta angle (in radians)
  91776. * @param radius defines radius
  91777. * @param target defines camera target
  91778. * @param interaxialDistance defines distance between each color axis
  91779. * @param scene defines the hosting scene
  91780. */
  91781. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91782. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91783. _this.interaxialDistance = interaxialDistance;
  91784. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91785. return _this;
  91786. }
  91787. /**
  91788. * Gets camera class name
  91789. * @returns AnaglyphArcRotateCamera
  91790. */
  91791. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91792. return "AnaglyphArcRotateCamera";
  91793. };
  91794. return AnaglyphArcRotateCamera;
  91795. }(BABYLON.ArcRotateCamera));
  91796. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91797. /**
  91798. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91799. */
  91800. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91801. __extends(AnaglyphGamepadCamera, _super);
  91802. /**
  91803. * Creates a new AnaglyphGamepadCamera
  91804. * @param name defines camera name
  91805. * @param position defines initial position
  91806. * @param interaxialDistance defines distance between each color axis
  91807. * @param scene defines the hosting scene
  91808. */
  91809. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91810. var _this = _super.call(this, name, position, scene) || this;
  91811. _this.interaxialDistance = interaxialDistance;
  91812. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91813. return _this;
  91814. }
  91815. /**
  91816. * Gets camera class name
  91817. * @returns AnaglyphGamepadCamera
  91818. */
  91819. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91820. return "AnaglyphGamepadCamera";
  91821. };
  91822. return AnaglyphGamepadCamera;
  91823. }(BABYLON.GamepadCamera));
  91824. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91825. /**
  91826. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91827. */
  91828. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91829. __extends(AnaglyphUniversalCamera, _super);
  91830. /**
  91831. * Creates a new AnaglyphUniversalCamera
  91832. * @param name defines camera name
  91833. * @param position defines initial position
  91834. * @param interaxialDistance defines distance between each color axis
  91835. * @param scene defines the hosting scene
  91836. */
  91837. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91838. var _this = _super.call(this, name, position, scene) || this;
  91839. _this.interaxialDistance = interaxialDistance;
  91840. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91841. return _this;
  91842. }
  91843. /**
  91844. * Gets camera class name
  91845. * @returns AnaglyphUniversalCamera
  91846. */
  91847. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91848. return "AnaglyphUniversalCamera";
  91849. };
  91850. return AnaglyphUniversalCamera;
  91851. }(BABYLON.UniversalCamera));
  91852. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91853. /**
  91854. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91855. */
  91856. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91857. __extends(StereoscopicFreeCamera, _super);
  91858. /**
  91859. * Creates a new StereoscopicFreeCamera
  91860. * @param name defines camera name
  91861. * @param position defines initial position
  91862. * @param interaxialDistance defines distance between each color axis
  91863. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91864. * @param scene defines the hosting scene
  91865. */
  91866. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91867. var _this = _super.call(this, name, position, scene) || this;
  91868. _this.interaxialDistance = interaxialDistance;
  91869. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91870. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91871. return _this;
  91872. }
  91873. /**
  91874. * Gets camera class name
  91875. * @returns StereoscopicFreeCamera
  91876. */
  91877. StereoscopicFreeCamera.prototype.getClassName = function () {
  91878. return "StereoscopicFreeCamera";
  91879. };
  91880. return StereoscopicFreeCamera;
  91881. }(BABYLON.FreeCamera));
  91882. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91883. /**
  91884. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91885. */
  91886. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91887. __extends(StereoscopicArcRotateCamera, _super);
  91888. /**
  91889. * Creates a new StereoscopicArcRotateCamera
  91890. * @param name defines camera name
  91891. * @param alpha defines alpha angle (in radians)
  91892. * @param beta defines beta angle (in radians)
  91893. * @param radius defines radius
  91894. * @param target defines camera target
  91895. * @param interaxialDistance defines distance between each color axis
  91896. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91897. * @param scene defines the hosting scene
  91898. */
  91899. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91900. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91901. _this.interaxialDistance = interaxialDistance;
  91902. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91903. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91904. return _this;
  91905. }
  91906. /**
  91907. * Gets camera class name
  91908. * @returns StereoscopicArcRotateCamera
  91909. */
  91910. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91911. return "StereoscopicArcRotateCamera";
  91912. };
  91913. return StereoscopicArcRotateCamera;
  91914. }(BABYLON.ArcRotateCamera));
  91915. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91916. /**
  91917. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91918. */
  91919. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91920. __extends(StereoscopicGamepadCamera, _super);
  91921. /**
  91922. * Creates a new StereoscopicGamepadCamera
  91923. * @param name defines camera name
  91924. * @param position defines initial position
  91925. * @param interaxialDistance defines distance between each color axis
  91926. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91927. * @param scene defines the hosting scene
  91928. */
  91929. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91930. var _this = _super.call(this, name, position, scene) || this;
  91931. _this.interaxialDistance = interaxialDistance;
  91932. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91933. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91934. return _this;
  91935. }
  91936. /**
  91937. * Gets camera class name
  91938. * @returns StereoscopicGamepadCamera
  91939. */
  91940. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91941. return "StereoscopicGamepadCamera";
  91942. };
  91943. return StereoscopicGamepadCamera;
  91944. }(BABYLON.GamepadCamera));
  91945. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91946. /**
  91947. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91948. */
  91949. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91950. __extends(StereoscopicUniversalCamera, _super);
  91951. /**
  91952. * Creates a new StereoscopicUniversalCamera
  91953. * @param name defines camera name
  91954. * @param position defines initial position
  91955. * @param interaxialDistance defines distance between each color axis
  91956. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91957. * @param scene defines the hosting scene
  91958. */
  91959. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91960. var _this = _super.call(this, name, position, scene) || this;
  91961. _this.interaxialDistance = interaxialDistance;
  91962. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91963. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91964. return _this;
  91965. }
  91966. /**
  91967. * Gets camera class name
  91968. * @returns StereoscopicUniversalCamera
  91969. */
  91970. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91971. return "StereoscopicUniversalCamera";
  91972. };
  91973. return StereoscopicUniversalCamera;
  91974. }(BABYLON.UniversalCamera));
  91975. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91976. })(BABYLON || (BABYLON = {}));
  91977. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  91978. var BABYLON;
  91979. (function (BABYLON) {
  91980. var VRExperienceHelperGazer = /** @class */ (function () {
  91981. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  91982. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  91983. this.scene = scene;
  91984. this._pointerDownOnMeshAsked = false;
  91985. this._isActionableMesh = false;
  91986. this._teleportationRequestInitiated = false;
  91987. this._teleportationBackRequestInitiated = false;
  91988. this._rotationRightAsked = false;
  91989. this._rotationLeftAsked = false;
  91990. this._dpadPressed = true;
  91991. this._activePointer = false;
  91992. this._id = VRExperienceHelperGazer._idCounter++;
  91993. // Gaze tracker
  91994. if (!gazeTrackerToClone) {
  91995. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  91996. this._gazeTracker.bakeCurrentTransformIntoVertices();
  91997. this._gazeTracker.isPickable = false;
  91998. this._gazeTracker.isVisible = false;
  91999. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  92000. targetMat.specularColor = BABYLON.Color3.Black();
  92001. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92002. targetMat.backFaceCulling = false;
  92003. this._gazeTracker.material = targetMat;
  92004. }
  92005. else {
  92006. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  92007. }
  92008. }
  92009. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  92010. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  92011. };
  92012. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  92013. this._pointerDownOnMeshAsked = true;
  92014. if (this._currentHit) {
  92015. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  92016. }
  92017. };
  92018. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  92019. if (this._currentHit) {
  92020. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  92021. }
  92022. this._pointerDownOnMeshAsked = false;
  92023. };
  92024. VRExperienceHelperGazer.prototype._activatePointer = function () {
  92025. this._activePointer = true;
  92026. };
  92027. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  92028. this._activePointer = false;
  92029. };
  92030. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  92031. if (distance === void 0) { distance = 100; }
  92032. };
  92033. VRExperienceHelperGazer.prototype.dispose = function () {
  92034. this._interactionsEnabled = false;
  92035. this._teleportationEnabled = false;
  92036. if (this._gazeTracker) {
  92037. this._gazeTracker.dispose();
  92038. }
  92039. };
  92040. VRExperienceHelperGazer._idCounter = 0;
  92041. return VRExperienceHelperGazer;
  92042. }());
  92043. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  92044. __extends(VRExperienceHelperControllerGazer, _super);
  92045. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  92046. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  92047. _this.webVRController = webVRController;
  92048. // Laser pointer
  92049. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  92050. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  92051. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  92052. laserPointerMaterial.alpha = 0.6;
  92053. _this._laserPointer.material = laserPointerMaterial;
  92054. _this._laserPointer.rotation.x = Math.PI / 2;
  92055. _this._laserPointer.position.z = -0.5;
  92056. _this._laserPointer.isVisible = false;
  92057. _this._laserPointer.isPickable = false;
  92058. if (!webVRController.mesh) {
  92059. // Create an empty mesh that is used prior to loading the high quality model
  92060. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  92061. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  92062. preloadPointerPose.rotation.x = -0.7;
  92063. preloadMesh.addChild(preloadPointerPose);
  92064. webVRController.attachToMesh(preloadMesh);
  92065. }
  92066. _this._setLaserPointerParent(webVRController.mesh);
  92067. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  92068. _this._setLaserPointerParent(mesh);
  92069. });
  92070. return _this;
  92071. }
  92072. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  92073. return this.webVRController.getForwardRay(length);
  92074. };
  92075. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  92076. _super.prototype._activatePointer.call(this);
  92077. this._laserPointer.isVisible = true;
  92078. };
  92079. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  92080. _super.prototype._deactivatePointer.call(this);
  92081. this._laserPointer.isVisible = false;
  92082. };
  92083. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  92084. this._laserPointer.material.emissiveColor = color;
  92085. };
  92086. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  92087. var makeNotPick = function (root) {
  92088. root.name += " laserPointer";
  92089. root.isPickable = false;
  92090. root.getChildMeshes().forEach(function (c) {
  92091. makeNotPick(c);
  92092. });
  92093. };
  92094. makeNotPick(mesh);
  92095. var childMeshes = mesh.getChildMeshes();
  92096. this.webVRController._pointingPoseNode = null;
  92097. for (var i = 0; i < childMeshes.length; i++) {
  92098. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  92099. mesh = childMeshes[i];
  92100. this.webVRController._pointingPoseNode = mesh;
  92101. break;
  92102. }
  92103. }
  92104. this._laserPointer.parent = mesh;
  92105. };
  92106. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  92107. if (distance === void 0) { distance = 100; }
  92108. this._laserPointer.scaling.y = distance;
  92109. this._laserPointer.position.z = -distance / 2;
  92110. };
  92111. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  92112. _super.prototype.dispose.call(this);
  92113. this._laserPointer.dispose();
  92114. if (this._meshAttachedObserver) {
  92115. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  92116. }
  92117. };
  92118. return VRExperienceHelperControllerGazer;
  92119. }(VRExperienceHelperGazer));
  92120. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  92121. __extends(VRExperienceHelperCameraGazer, _super);
  92122. function VRExperienceHelperCameraGazer(getCamera, scene) {
  92123. var _this = _super.call(this, scene) || this;
  92124. _this.getCamera = getCamera;
  92125. return _this;
  92126. }
  92127. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  92128. var camera = this.getCamera();
  92129. if (camera) {
  92130. return camera.getForwardRay(length);
  92131. }
  92132. else {
  92133. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  92134. }
  92135. };
  92136. return VRExperienceHelperCameraGazer;
  92137. }(VRExperienceHelperGazer));
  92138. /**
  92139. * Helps to quickly add VR support to an existing scene.
  92140. * See http://doc.babylonjs.com/how_to/webvr_helper
  92141. */
  92142. var VRExperienceHelper = /** @class */ (function () {
  92143. /**
  92144. * Instantiates a VRExperienceHelper.
  92145. * Helps to quickly add VR support to an existing scene.
  92146. * @param scene The scene the VRExperienceHelper belongs to.
  92147. * @param webVROptions Options to modify the vr experience helper's behavior.
  92148. */
  92149. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92150. if (webVROptions === void 0) { webVROptions = {}; }
  92151. var _this = this;
  92152. this.webVROptions = webVROptions;
  92153. // Can the system support WebVR, even if a headset isn't plugged in?
  92154. this._webVRsupported = false;
  92155. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92156. this._webVRready = false;
  92157. // Are we waiting for the requestPresent callback to complete?
  92158. this._webVRrequesting = false;
  92159. // Are we presenting to the headset right now?
  92160. this._webVRpresenting = false;
  92161. // Are we presenting in the fullscreen fallback?
  92162. this._fullscreenVRpresenting = false;
  92163. /**
  92164. * Observable raised when entering VR.
  92165. */
  92166. this.onEnteringVRObservable = new BABYLON.Observable();
  92167. /**
  92168. * Observable raised when exiting VR.
  92169. */
  92170. this.onExitingVRObservable = new BABYLON.Observable();
  92171. /**
  92172. * Observable raised when controller mesh is loaded.
  92173. */
  92174. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92175. this._useCustomVRButton = false;
  92176. this._teleportationRequested = false;
  92177. this._teleportActive = false;
  92178. this._floorMeshesCollection = [];
  92179. this._rotationAllowed = true;
  92180. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92181. this._isDefaultTeleportationTarget = true;
  92182. this._teleportationFillColor = "#444444";
  92183. this._teleportationBorderColor = "#FFFFFF";
  92184. this._rotationAngle = 0;
  92185. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92186. this._padSensibilityUp = 0.65;
  92187. this._padSensibilityDown = 0.35;
  92188. this.leftController = null;
  92189. this.rightController = null;
  92190. /**
  92191. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92192. */
  92193. this.onNewMeshSelected = new BABYLON.Observable();
  92194. /**
  92195. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92196. */
  92197. this.onNewMeshPicked = new BABYLON.Observable();
  92198. /**
  92199. * Observable raised before camera teleportation
  92200. */
  92201. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92202. /**
  92203. * Observable raised after camera teleportation
  92204. */
  92205. this.onAfterCameraTeleport = new BABYLON.Observable();
  92206. /**
  92207. * Observable raised when current selected mesh gets unselected
  92208. */
  92209. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92210. /**
  92211. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92212. */
  92213. this.teleportationEnabled = true;
  92214. this._teleportationInitialized = false;
  92215. this._interactionsEnabled = false;
  92216. this._interactionsRequested = false;
  92217. this._displayGaze = true;
  92218. this._displayLaserPointer = true;
  92219. this._onResize = function () {
  92220. _this.moveButtonToBottomRight();
  92221. if (_this._fullscreenVRpresenting && _this._webVRready) {
  92222. _this.exitVR();
  92223. }
  92224. };
  92225. this._onFullscreenChange = function () {
  92226. if (document.fullscreen !== undefined) {
  92227. _this._fullscreenVRpresenting = document.fullscreen;
  92228. }
  92229. else if (document.mozFullScreen !== undefined) {
  92230. _this._fullscreenVRpresenting = document.mozFullScreen;
  92231. }
  92232. else if (document.webkitIsFullScreen !== undefined) {
  92233. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  92234. }
  92235. else if (document.msIsFullScreen !== undefined) {
  92236. _this._fullscreenVRpresenting = document.msIsFullScreen;
  92237. }
  92238. else if (document.msFullscreenElement !== undefined) {
  92239. _this._fullscreenVRpresenting = document.msFullscreenElement;
  92240. }
  92241. if (!_this._fullscreenVRpresenting && _this._canvas) {
  92242. _this.exitVR();
  92243. if (!_this._useCustomVRButton) {
  92244. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  92245. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  92246. }
  92247. }
  92248. };
  92249. this.beforeRender = function () {
  92250. if (_this.leftController && _this.leftController._activePointer) {
  92251. _this._castRayAndSelectObject(_this.leftController);
  92252. }
  92253. if (_this.rightController && _this.rightController._activePointer) {
  92254. _this._castRayAndSelectObject(_this.rightController);
  92255. }
  92256. if (_this._noControllerIsActive) {
  92257. _this._castRayAndSelectObject(_this._cameraGazer);
  92258. }
  92259. else {
  92260. _this._cameraGazer._gazeTracker.isVisible = false;
  92261. }
  92262. };
  92263. this._onNewGamepadConnected = function (gamepad) {
  92264. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  92265. if (gamepad.leftStick) {
  92266. gamepad.onleftstickchanged(function (stickValues) {
  92267. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  92268. // Listening to classic/xbox gamepad only if no VR controller is active
  92269. if ((!_this.leftController && !_this.rightController) ||
  92270. ((_this.leftController && !_this.leftController._activePointer) &&
  92271. (_this.rightController && !_this.rightController._activePointer))) {
  92272. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  92273. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  92274. }
  92275. }
  92276. });
  92277. }
  92278. if (gamepad.rightStick) {
  92279. gamepad.onrightstickchanged(function (stickValues) {
  92280. if (_this._teleportationInitialized) {
  92281. _this._checkRotate(stickValues, _this._cameraGazer);
  92282. }
  92283. });
  92284. }
  92285. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  92286. gamepad.onbuttondown(function (buttonPressed) {
  92287. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92288. _this._cameraGazer._selectionPointerDown();
  92289. }
  92290. });
  92291. gamepad.onbuttonup(function (buttonPressed) {
  92292. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92293. _this._cameraGazer._selectionPointerUp();
  92294. }
  92295. });
  92296. }
  92297. }
  92298. else {
  92299. var webVRController = gamepad;
  92300. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  92301. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  92302. _this.rightController = controller;
  92303. }
  92304. else {
  92305. _this.leftController = controller;
  92306. }
  92307. _this._tryEnableInteractionOnController(controller);
  92308. }
  92309. };
  92310. // 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
  92311. this._tryEnableInteractionOnController = function (controller) {
  92312. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  92313. _this._enableInteractionOnController(controller);
  92314. }
  92315. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  92316. _this._enableTeleportationOnController(controller);
  92317. }
  92318. };
  92319. this._onNewGamepadDisconnected = function (gamepad) {
  92320. if (gamepad instanceof BABYLON.WebVRController) {
  92321. if (gamepad.hand === "left" && _this.leftController != null) {
  92322. _this.leftController.dispose();
  92323. _this.leftController = null;
  92324. }
  92325. if (gamepad.hand === "right" && _this.rightController != null) {
  92326. _this.rightController.dispose();
  92327. _this.rightController = null;
  92328. }
  92329. }
  92330. };
  92331. this._workingVector = BABYLON.Vector3.Zero();
  92332. this._workingQuaternion = BABYLON.Quaternion.Identity();
  92333. this._workingMatrix = BABYLON.Matrix.Identity();
  92334. this._scene = scene;
  92335. this._canvas = scene.getEngine().getRenderingCanvas();
  92336. // Parse options
  92337. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  92338. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  92339. }
  92340. if (webVROptions.createDeviceOrientationCamera === undefined) {
  92341. webVROptions.createDeviceOrientationCamera = true;
  92342. }
  92343. if (webVROptions.laserToggle === undefined) {
  92344. webVROptions.laserToggle = true;
  92345. }
  92346. if (webVROptions.defaultHeight === undefined) {
  92347. webVROptions.defaultHeight = 1.7;
  92348. }
  92349. if (webVROptions.useCustomVRButton) {
  92350. this._useCustomVRButton = true;
  92351. if (webVROptions.customVRButton) {
  92352. this._btnVR = webVROptions.customVRButton;
  92353. }
  92354. }
  92355. if (webVROptions.rayLength) {
  92356. this._rayLength = webVROptions.rayLength;
  92357. }
  92358. this._defaultHeight = webVROptions.defaultHeight;
  92359. if (webVROptions.positionScale) {
  92360. this._rayLength *= webVROptions.positionScale;
  92361. this._defaultHeight *= webVROptions.positionScale;
  92362. }
  92363. // Set position
  92364. if (this._scene.activeCamera) {
  92365. this._position = this._scene.activeCamera.position.clone();
  92366. }
  92367. else {
  92368. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  92369. }
  92370. // Set non-vr camera
  92371. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  92372. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  92373. // Copy data from existing camera
  92374. if (this._scene.activeCamera) {
  92375. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92376. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  92377. // Set rotation from previous camera
  92378. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  92379. var targetCamera = this._scene.activeCamera;
  92380. if (targetCamera.rotationQuaternion) {
  92381. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  92382. }
  92383. else {
  92384. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  92385. }
  92386. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  92387. }
  92388. }
  92389. this._scene.activeCamera = this._deviceOrientationCamera;
  92390. if (this._canvas) {
  92391. this._scene.activeCamera.attachControl(this._canvas);
  92392. }
  92393. }
  92394. else {
  92395. this._existingCamera = this._scene.activeCamera;
  92396. }
  92397. // Create VR cameras
  92398. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92399. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  92400. }
  92401. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  92402. this._webVRCamera.useStandingMatrix();
  92403. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  92404. // Create default button
  92405. if (!this._useCustomVRButton) {
  92406. this._btnVR = document.createElement("BUTTON");
  92407. this._btnVR.className = "babylonVRicon";
  92408. this._btnVR.id = "babylonVRiconbtn";
  92409. this._btnVR.title = "Click to switch to VR";
  92410. 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) }";
  92411. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  92412. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  92413. // css += ".babylonVRicon.vrdisplaysupported { }";
  92414. // css += ".babylonVRicon.vrdisplayready { }";
  92415. // css += ".babylonVRicon.vrdisplayrequesting { }";
  92416. var style = document.createElement('style');
  92417. style.appendChild(document.createTextNode(css));
  92418. document.getElementsByTagName('head')[0].appendChild(style);
  92419. this.moveButtonToBottomRight();
  92420. }
  92421. // VR button click event
  92422. if (this._btnVR) {
  92423. this._btnVR.addEventListener("click", function () {
  92424. if (!_this.isInVRMode) {
  92425. _this.enterVR();
  92426. }
  92427. else {
  92428. _this.exitVR();
  92429. }
  92430. });
  92431. }
  92432. // Window events
  92433. window.addEventListener("resize", this._onResize);
  92434. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92435. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92436. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92437. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92438. document.onmsfullscreenchange = this._onFullscreenChange;
  92439. // Display vr button when headset is connected
  92440. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92441. this.displayVRButton();
  92442. }
  92443. else {
  92444. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92445. if (e.vrDisplay) {
  92446. _this.displayVRButton();
  92447. }
  92448. });
  92449. }
  92450. // Exiting VR mode using 'ESC' key on desktop
  92451. this._onKeyDown = function (event) {
  92452. if (event.keyCode === 27 && _this.isInVRMode) {
  92453. _this.exitVR();
  92454. }
  92455. };
  92456. document.addEventListener("keydown", this._onKeyDown);
  92457. // Exiting VR mode double tapping the touch screen
  92458. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92459. if (_this.isInVRMode) {
  92460. _this.exitVR();
  92461. if (_this._fullscreenVRpresenting) {
  92462. _this._scene.getEngine().switchFullscreen(true);
  92463. }
  92464. }
  92465. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92466. // Listen for WebVR display changes
  92467. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92468. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92469. this._onVRRequestPresentStart = function () {
  92470. _this._webVRrequesting = true;
  92471. _this.updateButtonVisibility();
  92472. };
  92473. this._onVRRequestPresentComplete = function (success) {
  92474. _this._webVRrequesting = false;
  92475. _this.updateButtonVisibility();
  92476. };
  92477. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92478. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92479. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92480. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92481. scene.onDisposeObservable.add(function () {
  92482. _this.dispose();
  92483. });
  92484. // Gamepad connection events
  92485. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92486. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92487. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92488. this.updateButtonVisibility();
  92489. //create easing functions
  92490. this._circleEase = new BABYLON.CircleEase();
  92491. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92492. if (this.webVROptions.floorMeshes) {
  92493. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92494. }
  92495. }
  92496. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92497. /** Return this.onEnteringVRObservable
  92498. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  92499. */
  92500. get: function () {
  92501. return this.onEnteringVRObservable;
  92502. },
  92503. enumerable: true,
  92504. configurable: true
  92505. });
  92506. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  92507. /** Return this.onExitingVRObservable
  92508. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  92509. */
  92510. get: function () {
  92511. return this.onExitingVRObservable;
  92512. },
  92513. enumerable: true,
  92514. configurable: true
  92515. });
  92516. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  92517. /** Return this.onControllerMeshLoadedObservable
  92518. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  92519. */
  92520. get: function () {
  92521. return this.onControllerMeshLoadedObservable;
  92522. },
  92523. enumerable: true,
  92524. configurable: true
  92525. });
  92526. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  92527. /**
  92528. * The mesh used to display where the user is going to teleport.
  92529. */
  92530. get: function () {
  92531. return this._teleportationTarget;
  92532. },
  92533. /**
  92534. * Sets the mesh to be used to display where the user is going to teleport.
  92535. */
  92536. set: function (value) {
  92537. if (value) {
  92538. value.name = "teleportationTarget";
  92539. this._isDefaultTeleportationTarget = false;
  92540. this._teleportationTarget = value;
  92541. }
  92542. },
  92543. enumerable: true,
  92544. configurable: true
  92545. });
  92546. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  92547. /**
  92548. * The mesh used to display where the user is selecting,
  92549. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  92550. * See http://doc.babylonjs.com/resources/baking_transformations
  92551. */
  92552. get: function () {
  92553. return this._cameraGazer._gazeTracker;
  92554. },
  92555. set: function (value) {
  92556. if (value) {
  92557. this._cameraGazer._gazeTracker = value;
  92558. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  92559. this._cameraGazer._gazeTracker.isPickable = false;
  92560. this._cameraGazer._gazeTracker.isVisible = false;
  92561. this._cameraGazer._gazeTracker.name = "gazeTracker";
  92562. if (this.leftController) {
  92563. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92564. }
  92565. if (this.rightController) {
  92566. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92567. }
  92568. }
  92569. },
  92570. enumerable: true,
  92571. configurable: true
  92572. });
  92573. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  92574. /**
  92575. * If the ray of the gaze should be displayed.
  92576. */
  92577. get: function () {
  92578. return this._displayGaze;
  92579. },
  92580. /**
  92581. * Sets if the ray of the gaze should be displayed.
  92582. */
  92583. set: function (value) {
  92584. this._displayGaze = value;
  92585. if (!value) {
  92586. this._cameraGazer._gazeTracker.isVisible = false;
  92587. if (this.leftController) {
  92588. this.leftController._gazeTracker.isVisible = false;
  92589. }
  92590. if (this.rightController) {
  92591. this.rightController._gazeTracker.isVisible = false;
  92592. }
  92593. }
  92594. },
  92595. enumerable: true,
  92596. configurable: true
  92597. });
  92598. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  92599. /**
  92600. * If the ray of the LaserPointer should be displayed.
  92601. */
  92602. get: function () {
  92603. return this._displayLaserPointer;
  92604. },
  92605. /**
  92606. * Sets if the ray of the LaserPointer should be displayed.
  92607. */
  92608. set: function (value) {
  92609. this._displayLaserPointer = value;
  92610. if (!value) {
  92611. if (this.rightController) {
  92612. this.rightController._deactivatePointer();
  92613. this.rightController._gazeTracker.isVisible = false;
  92614. }
  92615. if (this.leftController) {
  92616. this.leftController._deactivatePointer();
  92617. this.leftController._gazeTracker.isVisible = false;
  92618. }
  92619. }
  92620. else {
  92621. if (this.rightController) {
  92622. this.rightController._activatePointer();
  92623. }
  92624. if (this.leftController) {
  92625. this.leftController._activatePointer();
  92626. }
  92627. }
  92628. },
  92629. enumerable: true,
  92630. configurable: true
  92631. });
  92632. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  92633. /**
  92634. * The deviceOrientationCamera used as the camera when not in VR.
  92635. */
  92636. get: function () {
  92637. return this._deviceOrientationCamera;
  92638. },
  92639. enumerable: true,
  92640. configurable: true
  92641. });
  92642. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  92643. /**
  92644. * Based on the current WebVR support, returns the current VR camera used.
  92645. */
  92646. get: function () {
  92647. if (this._webVRready) {
  92648. return this._webVRCamera;
  92649. }
  92650. else {
  92651. return this._scene.activeCamera;
  92652. }
  92653. },
  92654. enumerable: true,
  92655. configurable: true
  92656. });
  92657. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  92658. /**
  92659. * The webVRCamera which is used when in VR.
  92660. */
  92661. get: function () {
  92662. return this._webVRCamera;
  92663. },
  92664. enumerable: true,
  92665. configurable: true
  92666. });
  92667. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  92668. /**
  92669. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  92670. */
  92671. get: function () {
  92672. return this._vrDeviceOrientationCamera;
  92673. },
  92674. enumerable: true,
  92675. configurable: true
  92676. });
  92677. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  92678. get: function () {
  92679. var result = this._cameraGazer._teleportationRequestInitiated
  92680. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  92681. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  92682. return result;
  92683. },
  92684. enumerable: true,
  92685. configurable: true
  92686. });
  92687. // Raised when one of the controller has loaded successfully its associated default mesh
  92688. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  92689. if (this.leftController && this.leftController.webVRController == webVRController) {
  92690. if (webVRController.mesh) {
  92691. this.leftController._setLaserPointerParent(webVRController.mesh);
  92692. }
  92693. }
  92694. if (this.rightController && this.rightController.webVRController == webVRController) {
  92695. if (webVRController.mesh) {
  92696. this.rightController._setLaserPointerParent(webVRController.mesh);
  92697. }
  92698. }
  92699. try {
  92700. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  92701. }
  92702. catch (err) {
  92703. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  92704. }
  92705. };
  92706. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  92707. /**
  92708. * Gets a value indicating if we are currently in VR mode.
  92709. */
  92710. get: function () {
  92711. return this._webVRpresenting || this._fullscreenVRpresenting;
  92712. },
  92713. enumerable: true,
  92714. configurable: true
  92715. });
  92716. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  92717. var vrDisplay = this._scene.getEngine().getVRDevice();
  92718. if (vrDisplay) {
  92719. var wasPresenting = this._webVRpresenting;
  92720. // A VR display is connected
  92721. this._webVRpresenting = vrDisplay.isPresenting;
  92722. if (wasPresenting && !this._webVRpresenting)
  92723. this.exitVR();
  92724. }
  92725. else {
  92726. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  92727. }
  92728. this.updateButtonVisibility();
  92729. };
  92730. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  92731. this._webVRsupported = eventArgs.vrSupported;
  92732. this._webVRready = !!eventArgs.vrDisplay;
  92733. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  92734. this.updateButtonVisibility();
  92735. };
  92736. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  92737. if (this._canvas && !this._useCustomVRButton) {
  92738. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  92739. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  92740. }
  92741. };
  92742. VRExperienceHelper.prototype.displayVRButton = function () {
  92743. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  92744. document.body.appendChild(this._btnVR);
  92745. this._btnVRDisplayed = true;
  92746. }
  92747. };
  92748. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  92749. if (!this._btnVR || this._useCustomVRButton) {
  92750. return;
  92751. }
  92752. this._btnVR.className = "babylonVRicon";
  92753. if (this.isInVRMode) {
  92754. this._btnVR.className += " vrdisplaypresenting";
  92755. }
  92756. else {
  92757. if (this._webVRready)
  92758. this._btnVR.className += " vrdisplayready";
  92759. if (this._webVRsupported)
  92760. this._btnVR.className += " vrdisplaysupported";
  92761. if (this._webVRrequesting)
  92762. this._btnVR.className += " vrdisplayrequesting";
  92763. }
  92764. };
  92765. /**
  92766. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  92767. * Otherwise, will use the fullscreen API.
  92768. */
  92769. VRExperienceHelper.prototype.enterVR = function () {
  92770. if (this.onEnteringVRObservable) {
  92771. try {
  92772. this.onEnteringVRObservable.notifyObservers(this);
  92773. }
  92774. catch (err) {
  92775. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  92776. }
  92777. }
  92778. if (this._scene.activeCamera) {
  92779. this._position = this._scene.activeCamera.position.clone();
  92780. // make sure that we return to the last active camera
  92781. this._existingCamera = this._scene.activeCamera;
  92782. }
  92783. if (this._webVRrequesting)
  92784. return;
  92785. // If WebVR is supported and a headset is connected
  92786. if (this._webVRready) {
  92787. if (!this._webVRpresenting) {
  92788. this._webVRCamera.position = this._position;
  92789. this._scene.activeCamera = this._webVRCamera;
  92790. }
  92791. }
  92792. else if (this._vrDeviceOrientationCamera) {
  92793. this._vrDeviceOrientationCamera.position = this._position;
  92794. if (this._scene.activeCamera) {
  92795. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92796. }
  92797. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  92798. this._scene.getEngine().switchFullscreen(true);
  92799. this.updateButtonVisibility();
  92800. }
  92801. if (this._scene.activeCamera && this._canvas) {
  92802. this._scene.activeCamera.attachControl(this._canvas);
  92803. }
  92804. if (this._interactionsEnabled) {
  92805. this._scene.registerBeforeRender(this.beforeRender);
  92806. }
  92807. };
  92808. /**
  92809. * Attempt to exit VR, or fullscreen.
  92810. */
  92811. VRExperienceHelper.prototype.exitVR = function () {
  92812. if (this.onExitingVRObservable) {
  92813. try {
  92814. this.onExitingVRObservable.notifyObservers(this);
  92815. }
  92816. catch (err) {
  92817. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  92818. }
  92819. }
  92820. if (this._webVRpresenting) {
  92821. this._scene.getEngine().disableVR();
  92822. }
  92823. if (this._scene.activeCamera) {
  92824. this._position = this._scene.activeCamera.position.clone();
  92825. }
  92826. if (this._deviceOrientationCamera) {
  92827. this._deviceOrientationCamera.position = this._position;
  92828. this._scene.activeCamera = this._deviceOrientationCamera;
  92829. if (this._canvas) {
  92830. this._scene.activeCamera.attachControl(this._canvas);
  92831. }
  92832. }
  92833. else if (this._existingCamera) {
  92834. this._existingCamera.position = this._position;
  92835. this._scene.activeCamera = this._existingCamera;
  92836. }
  92837. this.updateButtonVisibility();
  92838. if (this._interactionsEnabled) {
  92839. this._scene.unregisterBeforeRender(this.beforeRender);
  92840. }
  92841. // resize to update width and height when exiting vr exits fullscreen
  92842. this._scene.getEngine().resize();
  92843. };
  92844. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  92845. /**
  92846. * The position of the vr experience helper.
  92847. */
  92848. get: function () {
  92849. return this._position;
  92850. },
  92851. /**
  92852. * Sets the position of the vr experience helper.
  92853. */
  92854. set: function (value) {
  92855. this._position = value;
  92856. if (this._scene.activeCamera) {
  92857. this._scene.activeCamera.position = value;
  92858. }
  92859. },
  92860. enumerable: true,
  92861. configurable: true
  92862. });
  92863. /**
  92864. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  92865. */
  92866. VRExperienceHelper.prototype.enableInteractions = function () {
  92867. var _this = this;
  92868. if (!this._interactionsEnabled) {
  92869. this._interactionsRequested = true;
  92870. if (this.leftController) {
  92871. this._enableInteractionOnController(this.leftController);
  92872. }
  92873. if (this.rightController) {
  92874. this._enableInteractionOnController(this.rightController);
  92875. }
  92876. this.raySelectionPredicate = function (mesh) {
  92877. return mesh.isVisible;
  92878. };
  92879. this.meshSelectionPredicate = function (mesh) {
  92880. return true;
  92881. };
  92882. this._raySelectionPredicate = function (mesh) {
  92883. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  92884. && mesh.name.indexOf("teleportationTarget") === -1
  92885. && mesh.name.indexOf("torusTeleportation") === -1
  92886. && mesh.name.indexOf("laserPointer") === -1)) {
  92887. return _this.raySelectionPredicate(mesh);
  92888. }
  92889. return false;
  92890. };
  92891. this._interactionsEnabled = true;
  92892. }
  92893. };
  92894. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  92895. get: function () {
  92896. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  92897. },
  92898. enumerable: true,
  92899. configurable: true
  92900. });
  92901. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  92902. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  92903. if (this._floorMeshesCollection[i].id === mesh.id) {
  92904. return true;
  92905. }
  92906. }
  92907. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  92908. return true;
  92909. }
  92910. return false;
  92911. };
  92912. /**
  92913. * Adds a floor mesh to be used for teleportation.
  92914. * @param floorMesh the mesh to be used for teleportation.
  92915. */
  92916. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  92917. if (!this._floorMeshesCollection) {
  92918. return;
  92919. }
  92920. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  92921. return;
  92922. }
  92923. this._floorMeshesCollection.push(floorMesh);
  92924. };
  92925. /**
  92926. * Removes a floor mesh from being used for teleportation.
  92927. * @param floorMesh the mesh to be removed.
  92928. */
  92929. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  92930. if (!this._floorMeshesCollection) {
  92931. return;
  92932. }
  92933. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  92934. if (meshIndex !== -1) {
  92935. this._floorMeshesCollection.splice(meshIndex, 1);
  92936. }
  92937. };
  92938. /**
  92939. * Enables interactions and teleportation using the VR controllers and gaze.
  92940. * @param vrTeleportationOptions options to modify teleportation behavior.
  92941. */
  92942. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  92943. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  92944. if (!this._teleportationInitialized) {
  92945. this._teleportationRequested = true;
  92946. this.enableInteractions();
  92947. if (vrTeleportationOptions.floorMeshName) {
  92948. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  92949. }
  92950. if (vrTeleportationOptions.floorMeshes) {
  92951. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  92952. }
  92953. if (this.leftController != null) {
  92954. this._enableTeleportationOnController(this.leftController);
  92955. }
  92956. if (this.rightController != null) {
  92957. this._enableTeleportationOnController(this.rightController);
  92958. }
  92959. // Creates an image processing post process for the vignette not relying
  92960. // on the main scene configuration for image processing to reduce setup and spaces
  92961. // (gamma/linear) conflicts.
  92962. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  92963. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  92964. imageProcessingConfiguration.vignetteEnabled = true;
  92965. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  92966. this._webVRCamera.detachPostProcess(this._postProcessMove);
  92967. this._teleportationInitialized = true;
  92968. if (this._isDefaultTeleportationTarget) {
  92969. this._createTeleportationCircles();
  92970. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  92971. }
  92972. }
  92973. };
  92974. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  92975. var _this = this;
  92976. var controllerMesh = controller.webVRController.mesh;
  92977. if (controllerMesh) {
  92978. controller._interactionsEnabled = true;
  92979. controller._activatePointer();
  92980. if (this.webVROptions.laserToggle) {
  92981. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  92982. // Enabling / disabling laserPointer
  92983. if (_this._displayLaserPointer && stateObject.value === 1) {
  92984. if (controller._activePointer) {
  92985. controller._deactivatePointer();
  92986. }
  92987. else {
  92988. controller._activatePointer();
  92989. }
  92990. if (_this.displayGaze) {
  92991. controller._gazeTracker.isVisible = controller._activePointer;
  92992. }
  92993. }
  92994. });
  92995. }
  92996. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  92997. var gazer = controller;
  92998. if (_this._noControllerIsActive) {
  92999. gazer = _this._cameraGazer;
  93000. }
  93001. if (!gazer._pointerDownOnMeshAsked) {
  93002. if (stateObject.value > _this._padSensibilityUp) {
  93003. gazer._selectionPointerDown();
  93004. }
  93005. }
  93006. else if (stateObject.value < _this._padSensibilityDown) {
  93007. gazer._selectionPointerUp();
  93008. }
  93009. });
  93010. }
  93011. };
  93012. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  93013. // Dont teleport if another gaze already requested teleportation
  93014. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  93015. return;
  93016. }
  93017. if (!gazer._teleportationRequestInitiated) {
  93018. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  93019. gazer._activatePointer();
  93020. gazer._teleportationRequestInitiated = true;
  93021. }
  93022. }
  93023. else {
  93024. // Listening to the proper controller values changes to confirm teleportation
  93025. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  93026. if (this._teleportActive) {
  93027. this._teleportCamera(this._haloCenter);
  93028. }
  93029. gazer._teleportationRequestInitiated = false;
  93030. }
  93031. }
  93032. };
  93033. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  93034. // Only rotate when user is not currently selecting a teleportation location
  93035. if (gazer._teleportationRequestInitiated) {
  93036. return;
  93037. }
  93038. if (!gazer._rotationLeftAsked) {
  93039. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  93040. gazer._rotationLeftAsked = true;
  93041. if (this._rotationAllowed) {
  93042. this._rotateCamera(false);
  93043. }
  93044. }
  93045. }
  93046. else {
  93047. if (stateObject.x > -this._padSensibilityDown) {
  93048. gazer._rotationLeftAsked = false;
  93049. }
  93050. }
  93051. if (!gazer._rotationRightAsked) {
  93052. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  93053. gazer._rotationRightAsked = true;
  93054. if (this._rotationAllowed) {
  93055. this._rotateCamera(true);
  93056. }
  93057. }
  93058. }
  93059. else {
  93060. if (stateObject.x < this._padSensibilityDown) {
  93061. gazer._rotationRightAsked = false;
  93062. }
  93063. }
  93064. };
  93065. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  93066. // Only teleport backwards when user is not currently selecting a teleportation location
  93067. if (gazer._teleportationRequestInitiated) {
  93068. return;
  93069. }
  93070. // Teleport backwards
  93071. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  93072. if (!gazer._teleportationBackRequestInitiated) {
  93073. if (!this.currentVRCamera) {
  93074. return;
  93075. }
  93076. // Get rotation and position of the current camera
  93077. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  93078. var position = this.currentVRCamera.position;
  93079. // If the camera has device position, use that instead
  93080. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  93081. rotation = this.currentVRCamera.deviceRotationQuaternion;
  93082. position = this.currentVRCamera.devicePosition;
  93083. }
  93084. // Get matrix with only the y rotation of the device rotation
  93085. rotation.toEulerAnglesToRef(this._workingVector);
  93086. this._workingVector.z = 0;
  93087. this._workingVector.x = 0;
  93088. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  93089. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  93090. // Rotate backwards ray by device rotation to cast at the ground behind the user
  93091. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  93092. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  93093. var ray = new BABYLON.Ray(position, this._workingVector);
  93094. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93095. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  93096. this._teleportCamera(hit.pickedPoint);
  93097. }
  93098. gazer._teleportationBackRequestInitiated = true;
  93099. }
  93100. }
  93101. else {
  93102. gazer._teleportationBackRequestInitiated = false;
  93103. }
  93104. };
  93105. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  93106. var _this = this;
  93107. var controllerMesh = controller.webVRController.mesh;
  93108. if (controllerMesh) {
  93109. if (!controller._interactionsEnabled) {
  93110. this._enableInteractionOnController(controller);
  93111. }
  93112. controller._interactionsEnabled = true;
  93113. controller._teleportationEnabled = true;
  93114. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93115. controller._dpadPressed = false;
  93116. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  93117. controller._dpadPressed = stateObject.pressed;
  93118. if (!controller._dpadPressed) {
  93119. controller._rotationLeftAsked = false;
  93120. controller._rotationRightAsked = false;
  93121. controller._teleportationBackRequestInitiated = false;
  93122. }
  93123. });
  93124. }
  93125. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  93126. if (_this.teleportationEnabled) {
  93127. _this._checkTeleportBackwards(stateObject, controller);
  93128. _this._checkTeleportWithRay(stateObject, controller);
  93129. }
  93130. _this._checkRotate(stateObject, controller);
  93131. });
  93132. }
  93133. };
  93134. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  93135. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  93136. this._teleportationTarget.isPickable = false;
  93137. var length = 512;
  93138. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  93139. dynamicTexture.hasAlpha = true;
  93140. var context = dynamicTexture.getContext();
  93141. var centerX = length / 2;
  93142. var centerY = length / 2;
  93143. var radius = 200;
  93144. context.beginPath();
  93145. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93146. context.fillStyle = this._teleportationFillColor;
  93147. context.fill();
  93148. context.lineWidth = 10;
  93149. context.strokeStyle = this._teleportationBorderColor;
  93150. context.stroke();
  93151. context.closePath();
  93152. dynamicTexture.update();
  93153. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93154. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93155. this._teleportationTarget.material = teleportationCircleMaterial;
  93156. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93157. torus.isPickable = false;
  93158. torus.parent = this._teleportationTarget;
  93159. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93160. var keys = [];
  93161. keys.push({
  93162. frame: 0,
  93163. value: 0
  93164. });
  93165. keys.push({
  93166. frame: 30,
  93167. value: 0.4
  93168. });
  93169. keys.push({
  93170. frame: 60,
  93171. value: 0
  93172. });
  93173. animationInnerCircle.setKeys(keys);
  93174. var easingFunction = new BABYLON.SineEase();
  93175. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93176. animationInnerCircle.setEasingFunction(easingFunction);
  93177. torus.animations = [];
  93178. torus.animations.push(animationInnerCircle);
  93179. this._scene.beginAnimation(torus, 0, 60, true);
  93180. this._hideTeleportationTarget();
  93181. };
  93182. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93183. this._teleportActive = true;
  93184. if (this._teleportationInitialized) {
  93185. this._teleportationTarget.isVisible = true;
  93186. if (this._isDefaultTeleportationTarget) {
  93187. this._teleportationTarget.getChildren()[0].isVisible = true;
  93188. }
  93189. }
  93190. };
  93191. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93192. this._teleportActive = false;
  93193. if (this._teleportationInitialized) {
  93194. this._teleportationTarget.isVisible = false;
  93195. if (this._isDefaultTeleportationTarget) {
  93196. this._teleportationTarget.getChildren()[0].isVisible = false;
  93197. }
  93198. }
  93199. };
  93200. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93201. var _this = this;
  93202. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93203. return;
  93204. }
  93205. if (right) {
  93206. this._rotationAngle++;
  93207. }
  93208. else {
  93209. this._rotationAngle--;
  93210. }
  93211. this.currentVRCamera.animations = [];
  93212. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93213. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93214. var animationRotationKeys = [];
  93215. animationRotationKeys.push({
  93216. frame: 0,
  93217. value: this.currentVRCamera.rotationQuaternion
  93218. });
  93219. animationRotationKeys.push({
  93220. frame: 6,
  93221. value: target
  93222. });
  93223. animationRotation.setKeys(animationRotationKeys);
  93224. animationRotation.setEasingFunction(this._circleEase);
  93225. this.currentVRCamera.animations.push(animationRotation);
  93226. this._postProcessMove.animations = [];
  93227. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93228. var vignetteWeightKeys = [];
  93229. vignetteWeightKeys.push({
  93230. frame: 0,
  93231. value: 0
  93232. });
  93233. vignetteWeightKeys.push({
  93234. frame: 3,
  93235. value: 4
  93236. });
  93237. vignetteWeightKeys.push({
  93238. frame: 6,
  93239. value: 0
  93240. });
  93241. animationPP.setKeys(vignetteWeightKeys);
  93242. animationPP.setEasingFunction(this._circleEase);
  93243. this._postProcessMove.animations.push(animationPP);
  93244. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93245. var vignetteStretchKeys = [];
  93246. vignetteStretchKeys.push({
  93247. frame: 0,
  93248. value: 0
  93249. });
  93250. vignetteStretchKeys.push({
  93251. frame: 3,
  93252. value: 10
  93253. });
  93254. vignetteStretchKeys.push({
  93255. frame: 6,
  93256. value: 0
  93257. });
  93258. animationPP2.setKeys(vignetteStretchKeys);
  93259. animationPP2.setEasingFunction(this._circleEase);
  93260. this._postProcessMove.animations.push(animationPP2);
  93261. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93262. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93263. this._postProcessMove.samples = 4;
  93264. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93265. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  93266. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93267. });
  93268. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  93269. };
  93270. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  93271. if (hit.pickedPoint) {
  93272. if (gazer._teleportationRequestInitiated) {
  93273. this._displayTeleportationTarget();
  93274. this._haloCenter.copyFrom(hit.pickedPoint);
  93275. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  93276. }
  93277. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  93278. if (pickNormal) {
  93279. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93280. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93281. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  93282. }
  93283. this._teleportationTarget.position.y += 0.1;
  93284. }
  93285. };
  93286. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93287. var _this = this;
  93288. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93289. return;
  93290. }
  93291. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93292. // offset of the headset from the anchor.
  93293. if (this.webVRCamera.leftCamera) {
  93294. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93295. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93296. location.subtractToRef(this._workingVector, this._workingVector);
  93297. }
  93298. else {
  93299. this._workingVector.copyFrom(location);
  93300. }
  93301. // Add height to account for user's height offset
  93302. if (this.isInVRMode) {
  93303. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  93304. }
  93305. else {
  93306. this._workingVector.y += this._defaultHeight;
  93307. }
  93308. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  93309. // Create animation from the camera's position to the new location
  93310. this.currentVRCamera.animations = [];
  93311. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93312. var animationCameraTeleportationKeys = [{
  93313. frame: 0,
  93314. value: this.currentVRCamera.position
  93315. },
  93316. {
  93317. frame: 11,
  93318. value: this._workingVector
  93319. }
  93320. ];
  93321. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  93322. animationCameraTeleportation.setEasingFunction(this._circleEase);
  93323. this.currentVRCamera.animations.push(animationCameraTeleportation);
  93324. this._postProcessMove.animations = [];
  93325. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93326. var vignetteWeightKeys = [];
  93327. vignetteWeightKeys.push({
  93328. frame: 0,
  93329. value: 0
  93330. });
  93331. vignetteWeightKeys.push({
  93332. frame: 5,
  93333. value: 8
  93334. });
  93335. vignetteWeightKeys.push({
  93336. frame: 11,
  93337. value: 0
  93338. });
  93339. animationPP.setKeys(vignetteWeightKeys);
  93340. this._postProcessMove.animations.push(animationPP);
  93341. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93342. var vignetteStretchKeys = [];
  93343. vignetteStretchKeys.push({
  93344. frame: 0,
  93345. value: 0
  93346. });
  93347. vignetteStretchKeys.push({
  93348. frame: 5,
  93349. value: 10
  93350. });
  93351. vignetteStretchKeys.push({
  93352. frame: 11,
  93353. value: 0
  93354. });
  93355. animationPP2.setKeys(vignetteStretchKeys);
  93356. this._postProcessMove.animations.push(animationPP2);
  93357. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93358. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93359. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93360. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  93361. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93362. });
  93363. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  93364. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  93365. });
  93366. this._hideTeleportationTarget();
  93367. };
  93368. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  93369. if (normal) {
  93370. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  93371. if (angle < Math.PI / 2) {
  93372. normal.scaleInPlace(-1);
  93373. }
  93374. }
  93375. return normal;
  93376. };
  93377. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  93378. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93379. return;
  93380. }
  93381. var ray = gazer._getForwardRay(this._rayLength);
  93382. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93383. if (hit) {
  93384. // Populate the contrllers mesh that can be used for drag/drop
  93385. if (gazer._laserPointer) {
  93386. hit.originMesh = gazer._laserPointer.parent;
  93387. }
  93388. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  93389. }
  93390. gazer._currentHit = hit;
  93391. // Moving the gazeTracker on the mesh face targetted
  93392. if (hit && hit.pickedPoint) {
  93393. if (this._displayGaze) {
  93394. var multiplier = 1;
  93395. gazer._gazeTracker.isVisible = true;
  93396. if (gazer._isActionableMesh) {
  93397. multiplier = 3;
  93398. }
  93399. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  93400. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  93401. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  93402. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  93403. // To avoid z-fighting
  93404. var deltaFighting = 0.002;
  93405. if (pickNormal) {
  93406. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93407. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93408. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  93409. }
  93410. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  93411. if (gazer._gazeTracker.position.x < 0) {
  93412. gazer._gazeTracker.position.x += deltaFighting;
  93413. }
  93414. else {
  93415. gazer._gazeTracker.position.x -= deltaFighting;
  93416. }
  93417. if (gazer._gazeTracker.position.y < 0) {
  93418. gazer._gazeTracker.position.y += deltaFighting;
  93419. }
  93420. else {
  93421. gazer._gazeTracker.position.y -= deltaFighting;
  93422. }
  93423. if (gazer._gazeTracker.position.z < 0) {
  93424. gazer._gazeTracker.position.z += deltaFighting;
  93425. }
  93426. else {
  93427. gazer._gazeTracker.position.z -= deltaFighting;
  93428. }
  93429. }
  93430. // Changing the size of the laser pointer based on the distance from the targetted point
  93431. gazer._updatePointerDistance(hit.distance);
  93432. }
  93433. else {
  93434. gazer._updatePointerDistance();
  93435. gazer._gazeTracker.isVisible = false;
  93436. }
  93437. if (hit && hit.pickedMesh) {
  93438. // The object selected is the floor, we're in a teleportation scenario
  93439. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93440. // Moving the teleportation area to this targetted point
  93441. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93442. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93443. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93444. }
  93445. gazer._currentMeshSelected = null;
  93446. if (gazer._teleportationRequestInitiated) {
  93447. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93448. }
  93449. return;
  93450. }
  93451. // If not, we're in a selection scenario
  93452. //this._teleportationAllowed = false;
  93453. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93454. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93455. this.onNewMeshPicked.notifyObservers(hit);
  93456. gazer._currentMeshSelected = hit.pickedMesh;
  93457. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93458. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93459. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93460. gazer._isActionableMesh = true;
  93461. }
  93462. else {
  93463. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93464. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93465. gazer._isActionableMesh = false;
  93466. }
  93467. try {
  93468. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93469. }
  93470. catch (err) {
  93471. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93472. }
  93473. }
  93474. else {
  93475. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93476. gazer._currentMeshSelected = null;
  93477. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93478. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93479. }
  93480. }
  93481. }
  93482. else {
  93483. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93484. gazer._currentMeshSelected = null;
  93485. //this._teleportationAllowed = false;
  93486. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93487. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93488. }
  93489. };
  93490. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93491. if (mesh) {
  93492. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93493. }
  93494. };
  93495. /**
  93496. * Sets the color of the laser ray from the vr controllers.
  93497. * @param color new color for the ray.
  93498. */
  93499. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  93500. if (this.leftController) {
  93501. this.leftController._setLaserPointerColor(color);
  93502. }
  93503. if (this.rightController) {
  93504. this.rightController._setLaserPointerColor(color);
  93505. }
  93506. };
  93507. /**
  93508. * Sets the color of the ray from the vr headsets gaze.
  93509. * @param color new color for the ray.
  93510. */
  93511. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  93512. if (!this._cameraGazer._gazeTracker.material) {
  93513. return;
  93514. }
  93515. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  93516. if (this.leftController) {
  93517. this.leftController._gazeTracker.material.emissiveColor = color;
  93518. }
  93519. if (this.rightController) {
  93520. this.rightController._gazeTracker.material.emissiveColor = color;
  93521. }
  93522. };
  93523. /**
  93524. * Exits VR and disposes of the vr experience helper
  93525. */
  93526. VRExperienceHelper.prototype.dispose = function () {
  93527. if (this.isInVRMode) {
  93528. this.exitVR();
  93529. }
  93530. if (this._postProcessMove) {
  93531. this._postProcessMove.dispose();
  93532. }
  93533. if (this._webVRCamera) {
  93534. this._webVRCamera.dispose();
  93535. }
  93536. if (this._vrDeviceOrientationCamera) {
  93537. this._vrDeviceOrientationCamera.dispose();
  93538. }
  93539. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  93540. document.body.removeChild(this._btnVR);
  93541. }
  93542. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  93543. this._deviceOrientationCamera.dispose();
  93544. }
  93545. if (this._cameraGazer) {
  93546. this._cameraGazer.dispose();
  93547. }
  93548. if (this.leftController) {
  93549. this.leftController.dispose();
  93550. }
  93551. if (this.rightController) {
  93552. this.rightController.dispose();
  93553. }
  93554. if (this._teleportationTarget) {
  93555. this._teleportationTarget.dispose();
  93556. }
  93557. this._floorMeshesCollection = [];
  93558. document.removeEventListener("keydown", this._onKeyDown);
  93559. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93560. window.removeEventListener("resize", this._onResize);
  93561. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  93562. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  93563. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  93564. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  93565. document.onmsfullscreenchange = null;
  93566. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  93567. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  93568. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  93569. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93570. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  93571. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  93572. this._scene.unregisterBeforeRender(this.beforeRender);
  93573. };
  93574. /**
  93575. * Gets the name of the VRExperienceHelper class
  93576. * @returns "VRExperienceHelper"
  93577. */
  93578. VRExperienceHelper.prototype.getClassName = function () {
  93579. return "VRExperienceHelper";
  93580. };
  93581. return VRExperienceHelper;
  93582. }());
  93583. BABYLON.VRExperienceHelper = VRExperienceHelper;
  93584. })(BABYLON || (BABYLON = {}));
  93585. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  93586. // Mainly based on these 2 articles :
  93587. // 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
  93588. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  93589. var BABYLON;
  93590. (function (BABYLON) {
  93591. /**
  93592. * Defines the potential axis of a Joystick
  93593. */
  93594. var JoystickAxis;
  93595. (function (JoystickAxis) {
  93596. /** X axis */
  93597. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  93598. /** Y axis */
  93599. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  93600. /** Z axis */
  93601. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  93602. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  93603. /**
  93604. * Class used to define virtual joystick (used in touch mode)
  93605. */
  93606. var VirtualJoystick = /** @class */ (function () {
  93607. /**
  93608. * Creates a new virtual joystick
  93609. * @param leftJoystick defines that the joystick is for left hand (false by default)
  93610. */
  93611. function VirtualJoystick(leftJoystick) {
  93612. var _this = this;
  93613. if (leftJoystick) {
  93614. this._leftJoystick = true;
  93615. }
  93616. else {
  93617. this._leftJoystick = false;
  93618. }
  93619. VirtualJoystick._globalJoystickIndex++;
  93620. // By default left & right arrow keys are moving the X
  93621. // and up & down keys are moving the Y
  93622. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93623. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93624. this.reverseLeftRight = false;
  93625. this.reverseUpDown = false;
  93626. // collections of pointers
  93627. this._touches = new BABYLON.StringDictionary();
  93628. this.deltaPosition = BABYLON.Vector3.Zero();
  93629. this._joystickSensibility = 25;
  93630. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93631. this._onResize = function (evt) {
  93632. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93633. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93634. if (VirtualJoystick.vjCanvas) {
  93635. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  93636. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  93637. }
  93638. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  93639. };
  93640. // injecting a canvas element on top of the canvas 3D game
  93641. if (!VirtualJoystick.vjCanvas) {
  93642. window.addEventListener("resize", this._onResize, false);
  93643. VirtualJoystick.vjCanvas = document.createElement("canvas");
  93644. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93645. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93646. VirtualJoystick.vjCanvas.width = window.innerWidth;
  93647. VirtualJoystick.vjCanvas.height = window.innerHeight;
  93648. VirtualJoystick.vjCanvas.style.width = "100%";
  93649. VirtualJoystick.vjCanvas.style.height = "100%";
  93650. VirtualJoystick.vjCanvas.style.position = "absolute";
  93651. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  93652. VirtualJoystick.vjCanvas.style.top = "0px";
  93653. VirtualJoystick.vjCanvas.style.left = "0px";
  93654. VirtualJoystick.vjCanvas.style.zIndex = "5";
  93655. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  93656. // Support for jQuery PEP polyfill
  93657. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  93658. var context = VirtualJoystick.vjCanvas.getContext('2d');
  93659. if (!context) {
  93660. throw new Error("Unable to create canvas for virtual joystick");
  93661. }
  93662. VirtualJoystick.vjCanvasContext = context;
  93663. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  93664. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93665. document.body.appendChild(VirtualJoystick.vjCanvas);
  93666. }
  93667. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  93668. this.pressed = false;
  93669. // default joystick color
  93670. this._joystickColor = "cyan";
  93671. this._joystickPointerID = -1;
  93672. // current joystick position
  93673. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  93674. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  93675. // origin joystick position
  93676. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  93677. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  93678. this._onPointerDownHandlerRef = function (evt) {
  93679. _this._onPointerDown(evt);
  93680. };
  93681. this._onPointerMoveHandlerRef = function (evt) {
  93682. _this._onPointerMove(evt);
  93683. };
  93684. this._onPointerUpHandlerRef = function (evt) {
  93685. _this._onPointerUp(evt);
  93686. };
  93687. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  93688. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  93689. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  93690. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  93691. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  93692. evt.preventDefault(); // Disables system menu
  93693. }, false);
  93694. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93695. }
  93696. /**
  93697. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  93698. * @param newJoystickSensibility defines the new sensibility
  93699. */
  93700. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  93701. this._joystickSensibility = newJoystickSensibility;
  93702. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93703. };
  93704. VirtualJoystick.prototype._onPointerDown = function (e) {
  93705. var positionOnScreenCondition;
  93706. e.preventDefault();
  93707. if (this._leftJoystick === true) {
  93708. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  93709. }
  93710. else {
  93711. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  93712. }
  93713. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  93714. // First contact will be dedicated to the virtual joystick
  93715. this._joystickPointerID = e.pointerId;
  93716. this._joystickPointerStartPos.x = e.clientX;
  93717. this._joystickPointerStartPos.y = e.clientY;
  93718. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  93719. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  93720. this._deltaJoystickVector.x = 0;
  93721. this._deltaJoystickVector.y = 0;
  93722. this.pressed = true;
  93723. this._touches.add(e.pointerId.toString(), e);
  93724. }
  93725. else {
  93726. // You can only trigger the action buttons with a joystick declared
  93727. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  93728. this._action();
  93729. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  93730. }
  93731. }
  93732. };
  93733. VirtualJoystick.prototype._onPointerMove = function (e) {
  93734. // If the current pointer is the one associated to the joystick (first touch contact)
  93735. if (this._joystickPointerID == e.pointerId) {
  93736. this._joystickPointerPos.x = e.clientX;
  93737. this._joystickPointerPos.y = e.clientY;
  93738. this._deltaJoystickVector = this._joystickPointerPos.clone();
  93739. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  93740. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  93741. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  93742. switch (this._axisTargetedByLeftAndRight) {
  93743. case JoystickAxis.X:
  93744. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  93745. break;
  93746. case JoystickAxis.Y:
  93747. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  93748. break;
  93749. case JoystickAxis.Z:
  93750. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  93751. break;
  93752. }
  93753. var directionUpDown = this.reverseUpDown ? 1 : -1;
  93754. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  93755. switch (this._axisTargetedByUpAndDown) {
  93756. case JoystickAxis.X:
  93757. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  93758. break;
  93759. case JoystickAxis.Y:
  93760. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  93761. break;
  93762. case JoystickAxis.Z:
  93763. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  93764. break;
  93765. }
  93766. }
  93767. else {
  93768. var data = this._touches.get(e.pointerId.toString());
  93769. if (data) {
  93770. data.x = e.clientX;
  93771. data.y = e.clientY;
  93772. }
  93773. }
  93774. };
  93775. VirtualJoystick.prototype._onPointerUp = function (e) {
  93776. if (this._joystickPointerID == e.pointerId) {
  93777. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  93778. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  93779. this._joystickPointerID = -1;
  93780. this.pressed = false;
  93781. }
  93782. else {
  93783. var touch = this._touches.get(e.pointerId.toString());
  93784. if (touch) {
  93785. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93786. }
  93787. }
  93788. this._deltaJoystickVector.x = 0;
  93789. this._deltaJoystickVector.y = 0;
  93790. this._touches.remove(e.pointerId.toString());
  93791. };
  93792. /**
  93793. * Change the color of the virtual joystick
  93794. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  93795. */
  93796. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  93797. this._joystickColor = newColor;
  93798. };
  93799. /**
  93800. * Defines a callback to call when the joystick is touched
  93801. * @param action defines the callback
  93802. */
  93803. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  93804. this._action = action;
  93805. };
  93806. /**
  93807. * Defines which axis you'd like to control for left & right
  93808. * @param axis defines the axis to use
  93809. */
  93810. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  93811. switch (axis) {
  93812. case JoystickAxis.X:
  93813. case JoystickAxis.Y:
  93814. case JoystickAxis.Z:
  93815. this._axisTargetedByLeftAndRight = axis;
  93816. break;
  93817. default:
  93818. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93819. break;
  93820. }
  93821. };
  93822. /**
  93823. * Defines which axis you'd like to control for up & down
  93824. * @param axis defines the axis to use
  93825. */
  93826. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  93827. switch (axis) {
  93828. case JoystickAxis.X:
  93829. case JoystickAxis.Y:
  93830. case JoystickAxis.Z:
  93831. this._axisTargetedByUpAndDown = axis;
  93832. break;
  93833. default:
  93834. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93835. break;
  93836. }
  93837. };
  93838. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  93839. var _this = this;
  93840. if (this.pressed) {
  93841. this._touches.forEach(function (key, touch) {
  93842. if (touch.pointerId === _this._joystickPointerID) {
  93843. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  93844. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  93845. VirtualJoystick.vjCanvasContext.beginPath();
  93846. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93847. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93848. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  93849. VirtualJoystick.vjCanvasContext.stroke();
  93850. VirtualJoystick.vjCanvasContext.closePath();
  93851. VirtualJoystick.vjCanvasContext.beginPath();
  93852. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93853. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93854. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  93855. VirtualJoystick.vjCanvasContext.stroke();
  93856. VirtualJoystick.vjCanvasContext.closePath();
  93857. VirtualJoystick.vjCanvasContext.beginPath();
  93858. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93859. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  93860. VirtualJoystick.vjCanvasContext.stroke();
  93861. VirtualJoystick.vjCanvasContext.closePath();
  93862. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  93863. }
  93864. else {
  93865. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93866. VirtualJoystick.vjCanvasContext.beginPath();
  93867. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  93868. VirtualJoystick.vjCanvasContext.beginPath();
  93869. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  93870. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93871. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  93872. VirtualJoystick.vjCanvasContext.stroke();
  93873. VirtualJoystick.vjCanvasContext.closePath();
  93874. touch.prevX = touch.x;
  93875. touch.prevY = touch.y;
  93876. }
  93877. ;
  93878. });
  93879. }
  93880. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93881. };
  93882. /**
  93883. * Release internal HTML canvas
  93884. */
  93885. VirtualJoystick.prototype.releaseCanvas = function () {
  93886. if (VirtualJoystick.vjCanvas) {
  93887. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  93888. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  93889. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  93890. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  93891. window.removeEventListener("resize", this._onResize);
  93892. document.body.removeChild(VirtualJoystick.vjCanvas);
  93893. VirtualJoystick.vjCanvas = null;
  93894. }
  93895. };
  93896. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  93897. VirtualJoystick._globalJoystickIndex = 0;
  93898. return VirtualJoystick;
  93899. }());
  93900. BABYLON.VirtualJoystick = VirtualJoystick;
  93901. })(BABYLON || (BABYLON = {}));
  93902. //# sourceMappingURL=babylon.virtualJoystick.js.map
  93903. var BABYLON;
  93904. (function (BABYLON) {
  93905. // We're mainly based on the logic defined into the FreeCamera code
  93906. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  93907. __extends(VirtualJoysticksCamera, _super);
  93908. function VirtualJoysticksCamera(name, position, scene) {
  93909. var _this = _super.call(this, name, position, scene) || this;
  93910. _this.inputs.addVirtualJoystick();
  93911. return _this;
  93912. }
  93913. VirtualJoysticksCamera.prototype.getClassName = function () {
  93914. return "VirtualJoysticksCamera";
  93915. };
  93916. return VirtualJoysticksCamera;
  93917. }(BABYLON.FreeCamera));
  93918. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  93919. })(BABYLON || (BABYLON = {}));
  93920. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  93921. var BABYLON;
  93922. (function (BABYLON) {
  93923. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  93924. function FreeCameraVirtualJoystickInput() {
  93925. }
  93926. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  93927. return this._leftjoystick;
  93928. };
  93929. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  93930. return this._rightjoystick;
  93931. };
  93932. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  93933. if (this._leftjoystick) {
  93934. var camera = this.camera;
  93935. var speed = camera._computeLocalCameraSpeed() * 50;
  93936. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  93937. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  93938. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  93939. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  93940. if (!this._leftjoystick.pressed) {
  93941. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  93942. }
  93943. if (!this._rightjoystick.pressed) {
  93944. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  93945. }
  93946. }
  93947. };
  93948. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  93949. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  93950. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  93951. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  93952. this._leftjoystick.setJoystickSensibility(0.15);
  93953. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  93954. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  93955. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  93956. this._rightjoystick.reverseUpDown = true;
  93957. this._rightjoystick.setJoystickSensibility(0.05);
  93958. this._rightjoystick.setJoystickColor("yellow");
  93959. };
  93960. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  93961. this._leftjoystick.releaseCanvas();
  93962. this._rightjoystick.releaseCanvas();
  93963. };
  93964. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  93965. return "FreeCameraVirtualJoystickInput";
  93966. };
  93967. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  93968. return "virtualJoystick";
  93969. };
  93970. return FreeCameraVirtualJoystickInput;
  93971. }());
  93972. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  93973. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  93974. })(BABYLON || (BABYLON = {}));
  93975. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  93976. var BABYLON;
  93977. (function (BABYLON) {
  93978. var SimplificationSettings = /** @class */ (function () {
  93979. function SimplificationSettings(quality, distance, optimizeMesh) {
  93980. this.quality = quality;
  93981. this.distance = distance;
  93982. this.optimizeMesh = optimizeMesh;
  93983. }
  93984. return SimplificationSettings;
  93985. }());
  93986. BABYLON.SimplificationSettings = SimplificationSettings;
  93987. var SimplificationQueue = /** @class */ (function () {
  93988. function SimplificationQueue() {
  93989. this.running = false;
  93990. this._simplificationArray = [];
  93991. }
  93992. SimplificationQueue.prototype.addTask = function (task) {
  93993. this._simplificationArray.push(task);
  93994. };
  93995. SimplificationQueue.prototype.executeNext = function () {
  93996. var task = this._simplificationArray.pop();
  93997. if (task) {
  93998. this.running = true;
  93999. this.runSimplification(task);
  94000. }
  94001. else {
  94002. this.running = false;
  94003. }
  94004. };
  94005. SimplificationQueue.prototype.runSimplification = function (task) {
  94006. var _this = this;
  94007. if (task.parallelProcessing) {
  94008. //parallel simplifier
  94009. task.settings.forEach(function (setting) {
  94010. var simplifier = _this.getSimplifier(task);
  94011. simplifier.simplify(setting, function (newMesh) {
  94012. task.mesh.addLODLevel(setting.distance, newMesh);
  94013. newMesh.isVisible = true;
  94014. //check if it is the last
  94015. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  94016. //all done, run the success callback.
  94017. task.successCallback();
  94018. }
  94019. _this.executeNext();
  94020. });
  94021. });
  94022. }
  94023. else {
  94024. //single simplifier.
  94025. var simplifier = this.getSimplifier(task);
  94026. var runDecimation = function (setting, callback) {
  94027. simplifier.simplify(setting, function (newMesh) {
  94028. task.mesh.addLODLevel(setting.distance, newMesh);
  94029. newMesh.isVisible = true;
  94030. //run the next quality level
  94031. callback();
  94032. });
  94033. };
  94034. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  94035. runDecimation(task.settings[loop.index], function () {
  94036. loop.executeNext();
  94037. });
  94038. }, function () {
  94039. //execution ended, run the success callback.
  94040. if (task.successCallback) {
  94041. task.successCallback();
  94042. }
  94043. _this.executeNext();
  94044. });
  94045. }
  94046. };
  94047. SimplificationQueue.prototype.getSimplifier = function (task) {
  94048. switch (task.simplificationType) {
  94049. case SimplificationType.QUADRATIC:
  94050. default:
  94051. return new QuadraticErrorSimplification(task.mesh);
  94052. }
  94053. };
  94054. return SimplificationQueue;
  94055. }());
  94056. BABYLON.SimplificationQueue = SimplificationQueue;
  94057. /**
  94058. * The implemented types of simplification
  94059. * At the moment only Quadratic Error Decimation is implemented
  94060. */
  94061. var SimplificationType;
  94062. (function (SimplificationType) {
  94063. /** Quadratic error decimation */
  94064. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  94065. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  94066. var DecimationTriangle = /** @class */ (function () {
  94067. function DecimationTriangle(vertices) {
  94068. this.vertices = vertices;
  94069. this.error = new Array(4);
  94070. this.deleted = false;
  94071. this.isDirty = false;
  94072. this.deletePending = false;
  94073. this.borderFactor = 0;
  94074. }
  94075. return DecimationTriangle;
  94076. }());
  94077. BABYLON.DecimationTriangle = DecimationTriangle;
  94078. var DecimationVertex = /** @class */ (function () {
  94079. function DecimationVertex(position, id) {
  94080. this.position = position;
  94081. this.id = id;
  94082. this.isBorder = true;
  94083. this.q = new QuadraticMatrix();
  94084. this.triangleCount = 0;
  94085. this.triangleStart = 0;
  94086. this.originalOffsets = [];
  94087. }
  94088. DecimationVertex.prototype.updatePosition = function (newPosition) {
  94089. this.position.copyFrom(newPosition);
  94090. };
  94091. return DecimationVertex;
  94092. }());
  94093. BABYLON.DecimationVertex = DecimationVertex;
  94094. var QuadraticMatrix = /** @class */ (function () {
  94095. function QuadraticMatrix(data) {
  94096. this.data = new Array(10);
  94097. for (var i = 0; i < 10; ++i) {
  94098. if (data && data[i]) {
  94099. this.data[i] = data[i];
  94100. }
  94101. else {
  94102. this.data[i] = 0;
  94103. }
  94104. }
  94105. }
  94106. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  94107. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  94108. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  94109. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  94110. return det;
  94111. };
  94112. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  94113. for (var i = 0; i < 10; ++i) {
  94114. this.data[i] += matrix.data[i];
  94115. }
  94116. };
  94117. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  94118. for (var i = 0; i < 10; ++i) {
  94119. this.data[i] += data[i];
  94120. }
  94121. };
  94122. QuadraticMatrix.prototype.add = function (matrix) {
  94123. var m = new QuadraticMatrix();
  94124. for (var i = 0; i < 10; ++i) {
  94125. m.data[i] = this.data[i] + matrix.data[i];
  94126. }
  94127. return m;
  94128. };
  94129. QuadraticMatrix.FromData = function (a, b, c, d) {
  94130. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  94131. };
  94132. //returning an array to avoid garbage collection
  94133. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  94134. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  94135. };
  94136. return QuadraticMatrix;
  94137. }());
  94138. BABYLON.QuadraticMatrix = QuadraticMatrix;
  94139. var Reference = /** @class */ (function () {
  94140. function Reference(vertexId, triangleId) {
  94141. this.vertexId = vertexId;
  94142. this.triangleId = triangleId;
  94143. }
  94144. return Reference;
  94145. }());
  94146. BABYLON.Reference = Reference;
  94147. /**
  94148. * An implementation of the Quadratic Error simplification algorithm.
  94149. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94150. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94151. * @author RaananW
  94152. */
  94153. var QuadraticErrorSimplification = /** @class */ (function () {
  94154. function QuadraticErrorSimplification(_mesh) {
  94155. this._mesh = _mesh;
  94156. this.syncIterations = 5000;
  94157. this.aggressiveness = 7;
  94158. this.decimationIterations = 100;
  94159. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94160. }
  94161. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94162. var _this = this;
  94163. this.initDecimatedMesh();
  94164. //iterating through the submeshes array, one after the other.
  94165. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94166. _this.initWithMesh(loop.index, function () {
  94167. _this.runDecimation(settings, loop.index, function () {
  94168. loop.executeNext();
  94169. });
  94170. }, settings.optimizeMesh);
  94171. }, function () {
  94172. setTimeout(function () {
  94173. successCallback(_this._reconstructedMesh);
  94174. }, 0);
  94175. });
  94176. };
  94177. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94178. var _this = this;
  94179. var targetCount = ~~(this.triangles.length * settings.quality);
  94180. var deletedTriangles = 0;
  94181. var triangleCount = this.triangles.length;
  94182. var iterationFunction = function (iteration, callback) {
  94183. setTimeout(function () {
  94184. if (iteration % 5 === 0) {
  94185. _this.updateMesh(iteration === 0);
  94186. }
  94187. for (var i = 0; i < _this.triangles.length; ++i) {
  94188. _this.triangles[i].isDirty = false;
  94189. }
  94190. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94191. var trianglesIterator = function (i) {
  94192. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94193. var t = _this.triangles[tIdx];
  94194. if (!t)
  94195. return;
  94196. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94197. return;
  94198. }
  94199. for (var j = 0; j < 3; ++j) {
  94200. if (t.error[j] < threshold) {
  94201. var deleted0 = [];
  94202. var deleted1 = [];
  94203. var v0 = t.vertices[j];
  94204. var v1 = t.vertices[(j + 1) % 3];
  94205. if (v0.isBorder || v1.isBorder)
  94206. continue;
  94207. var p = BABYLON.Vector3.Zero();
  94208. var n = BABYLON.Vector3.Zero();
  94209. var uv = BABYLON.Vector2.Zero();
  94210. var color = new BABYLON.Color4(0, 0, 0, 1);
  94211. _this.calculateError(v0, v1, p, n, uv, color);
  94212. var delTr = new Array();
  94213. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94214. continue;
  94215. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  94216. continue;
  94217. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  94218. continue;
  94219. var uniqueArray = new Array();
  94220. delTr.forEach(function (deletedT) {
  94221. if (uniqueArray.indexOf(deletedT) === -1) {
  94222. deletedT.deletePending = true;
  94223. uniqueArray.push(deletedT);
  94224. }
  94225. });
  94226. if (uniqueArray.length % 2 !== 0) {
  94227. continue;
  94228. }
  94229. v0.q = v1.q.add(v0.q);
  94230. v0.updatePosition(p);
  94231. var tStart = _this.references.length;
  94232. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  94233. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  94234. var tCount = _this.references.length - tStart;
  94235. if (tCount <= v0.triangleCount) {
  94236. if (tCount) {
  94237. for (var c = 0; c < tCount; c++) {
  94238. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  94239. }
  94240. }
  94241. }
  94242. else {
  94243. v0.triangleStart = tStart;
  94244. }
  94245. v0.triangleCount = tCount;
  94246. break;
  94247. }
  94248. }
  94249. };
  94250. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  94251. }, 0);
  94252. };
  94253. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  94254. if (triangleCount - deletedTriangles <= targetCount)
  94255. loop.breakLoop();
  94256. else {
  94257. iterationFunction(loop.index, function () {
  94258. loop.executeNext();
  94259. });
  94260. }
  94261. }, function () {
  94262. setTimeout(function () {
  94263. //reconstruct this part of the mesh
  94264. _this.reconstructMesh(submeshIndex);
  94265. successCallback();
  94266. }, 0);
  94267. });
  94268. };
  94269. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  94270. var _this = this;
  94271. this.vertices = [];
  94272. this.triangles = [];
  94273. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94274. var indices = this._mesh.getIndices();
  94275. var submesh = this._mesh.subMeshes[submeshIndex];
  94276. var findInVertices = function (positionToSearch) {
  94277. if (optimizeMesh) {
  94278. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  94279. if (_this.vertices[ii].position.equals(positionToSearch)) {
  94280. return _this.vertices[ii];
  94281. }
  94282. }
  94283. }
  94284. return null;
  94285. };
  94286. var vertexReferences = [];
  94287. var vertexInit = function (i) {
  94288. if (!positionData) {
  94289. return;
  94290. }
  94291. var offset = i + submesh.verticesStart;
  94292. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94293. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94294. vertex.originalOffsets.push(offset);
  94295. if (vertex.id === _this.vertices.length) {
  94296. _this.vertices.push(vertex);
  94297. }
  94298. vertexReferences.push(vertex.id);
  94299. };
  94300. //var totalVertices = mesh.getTotalVertices();
  94301. var totalVertices = submesh.verticesCount;
  94302. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  94303. var indicesInit = function (i) {
  94304. if (!indices) {
  94305. return;
  94306. }
  94307. var offset = (submesh.indexStart / 3) + i;
  94308. var pos = (offset * 3);
  94309. var i0 = indices[pos + 0];
  94310. var i1 = indices[pos + 1];
  94311. var i2 = indices[pos + 2];
  94312. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  94313. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  94314. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  94315. var triangle = new DecimationTriangle([v0, v1, v2]);
  94316. triangle.originalOffset = pos;
  94317. _this.triangles.push(triangle);
  94318. };
  94319. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  94320. _this.init(callback);
  94321. });
  94322. });
  94323. };
  94324. QuadraticErrorSimplification.prototype.init = function (callback) {
  94325. var _this = this;
  94326. var triangleInit1 = function (i) {
  94327. var t = _this.triangles[i];
  94328. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  94329. for (var j = 0; j < 3; j++) {
  94330. 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))));
  94331. }
  94332. };
  94333. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  94334. var triangleInit2 = function (i) {
  94335. var t = _this.triangles[i];
  94336. for (var j = 0; j < 3; ++j) {
  94337. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  94338. }
  94339. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94340. };
  94341. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  94342. callback();
  94343. });
  94344. });
  94345. };
  94346. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  94347. var newTriangles = [];
  94348. var i;
  94349. for (i = 0; i < this.vertices.length; ++i) {
  94350. this.vertices[i].triangleCount = 0;
  94351. }
  94352. var t;
  94353. var j;
  94354. for (i = 0; i < this.triangles.length; ++i) {
  94355. if (!this.triangles[i].deleted) {
  94356. t = this.triangles[i];
  94357. for (j = 0; j < 3; ++j) {
  94358. t.vertices[j].triangleCount = 1;
  94359. }
  94360. newTriangles.push(t);
  94361. }
  94362. }
  94363. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  94364. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  94365. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  94366. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  94367. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  94368. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94369. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  94370. var vertexCount = 0;
  94371. for (i = 0; i < this.vertices.length; ++i) {
  94372. var vertex = this.vertices[i];
  94373. vertex.id = vertexCount;
  94374. if (vertex.triangleCount) {
  94375. vertex.originalOffsets.forEach(function (originalOffset) {
  94376. if (!normalData) {
  94377. return;
  94378. }
  94379. newPositionData.push(vertex.position.x);
  94380. newPositionData.push(vertex.position.y);
  94381. newPositionData.push(vertex.position.z);
  94382. newNormalData.push(normalData[originalOffset * 3]);
  94383. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  94384. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  94385. if (uvs && uvs.length) {
  94386. newUVsData.push(uvs[(originalOffset * 2)]);
  94387. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  94388. }
  94389. else if (colorsData && colorsData.length) {
  94390. newColorsData.push(colorsData[(originalOffset * 4)]);
  94391. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  94392. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  94393. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  94394. }
  94395. ++vertexCount;
  94396. });
  94397. }
  94398. }
  94399. var startingIndex = this._reconstructedMesh.getTotalIndices();
  94400. var startingVertex = this._reconstructedMesh.getTotalVertices();
  94401. var submeshesArray = this._reconstructedMesh.subMeshes;
  94402. this._reconstructedMesh.subMeshes = [];
  94403. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  94404. var originalIndices = this._mesh.getIndices();
  94405. for (i = 0; i < newTriangles.length; ++i) {
  94406. t = newTriangles[i]; //now get the new referencing point for each vertex
  94407. [0, 1, 2].forEach(function (idx) {
  94408. var id = originalIndices[t.originalOffset + idx];
  94409. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  94410. if (offset < 0)
  94411. offset = 0;
  94412. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  94413. });
  94414. }
  94415. //overwriting the old vertex buffers and indices.
  94416. this._reconstructedMesh.setIndices(newIndicesArray);
  94417. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  94418. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  94419. if (newUVsData.length > 0)
  94420. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  94421. if (newColorsData.length > 0)
  94422. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  94423. //create submesh
  94424. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  94425. if (submeshIndex > 0) {
  94426. this._reconstructedMesh.subMeshes = [];
  94427. submeshesArray.forEach(function (submesh) {
  94428. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94429. });
  94430. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94431. }
  94432. };
  94433. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94434. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94435. this._reconstructedMesh.material = this._mesh.material;
  94436. this._reconstructedMesh.parent = this._mesh.parent;
  94437. this._reconstructedMesh.isVisible = false;
  94438. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94439. };
  94440. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94441. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94442. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94443. if (t.deleted)
  94444. continue;
  94445. var s = this.references[vertex1.triangleStart + i].vertexId;
  94446. var v1 = t.vertices[(s + 1) % 3];
  94447. var v2 = t.vertices[(s + 2) % 3];
  94448. if ((v1 === vertex2 || v2 === vertex2)) {
  94449. deletedArray[i] = true;
  94450. delTr.push(t);
  94451. continue;
  94452. }
  94453. var d1 = v1.position.subtract(point);
  94454. d1 = d1.normalize();
  94455. var d2 = v2.position.subtract(point);
  94456. d2 = d2.normalize();
  94457. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94458. return true;
  94459. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94460. deletedArray[i] = false;
  94461. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94462. return true;
  94463. }
  94464. return false;
  94465. };
  94466. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94467. var newDeleted = deletedTriangles;
  94468. for (var i = 0; i < vertex.triangleCount; ++i) {
  94469. var ref = this.references[vertex.triangleStart + i];
  94470. var t = this.triangles[ref.triangleId];
  94471. if (t.deleted)
  94472. continue;
  94473. if (deletedArray[i] && t.deletePending) {
  94474. t.deleted = true;
  94475. newDeleted++;
  94476. continue;
  94477. }
  94478. t.vertices[ref.vertexId] = origVertex;
  94479. t.isDirty = true;
  94480. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94481. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94482. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94483. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94484. this.references.push(ref);
  94485. }
  94486. return newDeleted;
  94487. };
  94488. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94489. for (var i = 0; i < this.vertices.length; ++i) {
  94490. var vCount = [];
  94491. var vId = [];
  94492. var v = this.vertices[i];
  94493. var j;
  94494. for (j = 0; j < v.triangleCount; ++j) {
  94495. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  94496. for (var ii = 0; ii < 3; ii++) {
  94497. var ofs = 0;
  94498. var vv = triangle.vertices[ii];
  94499. while (ofs < vCount.length) {
  94500. if (vId[ofs] === vv.id)
  94501. break;
  94502. ++ofs;
  94503. }
  94504. if (ofs === vCount.length) {
  94505. vCount.push(1);
  94506. vId.push(vv.id);
  94507. }
  94508. else {
  94509. vCount[ofs]++;
  94510. }
  94511. }
  94512. }
  94513. for (j = 0; j < vCount.length; ++j) {
  94514. if (vCount[j] === 1) {
  94515. this.vertices[vId[j]].isBorder = true;
  94516. }
  94517. else {
  94518. this.vertices[vId[j]].isBorder = false;
  94519. }
  94520. }
  94521. }
  94522. };
  94523. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  94524. if (identifyBorders === void 0) { identifyBorders = false; }
  94525. var i;
  94526. if (!identifyBorders) {
  94527. var newTrianglesVector = [];
  94528. for (i = 0; i < this.triangles.length; ++i) {
  94529. if (!this.triangles[i].deleted) {
  94530. newTrianglesVector.push(this.triangles[i]);
  94531. }
  94532. }
  94533. this.triangles = newTrianglesVector;
  94534. }
  94535. for (i = 0; i < this.vertices.length; ++i) {
  94536. this.vertices[i].triangleCount = 0;
  94537. this.vertices[i].triangleStart = 0;
  94538. }
  94539. var t;
  94540. var j;
  94541. var v;
  94542. for (i = 0; i < this.triangles.length; ++i) {
  94543. t = this.triangles[i];
  94544. for (j = 0; j < 3; ++j) {
  94545. v = t.vertices[j];
  94546. v.triangleCount++;
  94547. }
  94548. }
  94549. var tStart = 0;
  94550. for (i = 0; i < this.vertices.length; ++i) {
  94551. this.vertices[i].triangleStart = tStart;
  94552. tStart += this.vertices[i].triangleCount;
  94553. this.vertices[i].triangleCount = 0;
  94554. }
  94555. var newReferences = new Array(this.triangles.length * 3);
  94556. for (i = 0; i < this.triangles.length; ++i) {
  94557. t = this.triangles[i];
  94558. for (j = 0; j < 3; ++j) {
  94559. v = t.vertices[j];
  94560. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  94561. v.triangleCount++;
  94562. }
  94563. }
  94564. this.references = newReferences;
  94565. if (identifyBorders) {
  94566. this.identifyBorder();
  94567. }
  94568. };
  94569. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  94570. var x = point.x;
  94571. var y = point.y;
  94572. var z = point.z;
  94573. 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
  94574. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  94575. };
  94576. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  94577. var q = vertex1.q.add(vertex2.q);
  94578. var border = vertex1.isBorder && vertex2.isBorder;
  94579. var error = 0;
  94580. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  94581. if (qDet !== 0 && !border) {
  94582. if (!pointResult) {
  94583. pointResult = BABYLON.Vector3.Zero();
  94584. }
  94585. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  94586. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  94587. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  94588. error = this.vertexError(q, pointResult);
  94589. }
  94590. else {
  94591. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  94592. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  94593. var error1 = this.vertexError(q, vertex1.position);
  94594. var error2 = this.vertexError(q, vertex2.position);
  94595. var error3 = this.vertexError(q, p3);
  94596. error = Math.min(error1, error2, error3);
  94597. if (error === error1) {
  94598. if (pointResult) {
  94599. pointResult.copyFrom(vertex1.position);
  94600. }
  94601. }
  94602. else if (error === error2) {
  94603. if (pointResult) {
  94604. pointResult.copyFrom(vertex2.position);
  94605. }
  94606. }
  94607. else {
  94608. if (pointResult) {
  94609. pointResult.copyFrom(p3);
  94610. }
  94611. }
  94612. }
  94613. return error;
  94614. };
  94615. return QuadraticErrorSimplification;
  94616. }());
  94617. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  94618. })(BABYLON || (BABYLON = {}));
  94619. //# sourceMappingURL=babylon.meshSimplification.js.map
  94620. var BABYLON;
  94621. (function (BABYLON) {
  94622. var MeshLODLevel = /** @class */ (function () {
  94623. function MeshLODLevel(distance, mesh) {
  94624. this.distance = distance;
  94625. this.mesh = mesh;
  94626. }
  94627. return MeshLODLevel;
  94628. }());
  94629. BABYLON.MeshLODLevel = MeshLODLevel;
  94630. })(BABYLON || (BABYLON = {}));
  94631. //# sourceMappingURL=babylon.meshLODLevel.js.map
  94632. var BABYLON;
  94633. (function (BABYLON) {
  94634. /**
  94635. * Defines the root class used to create scene optimization to use with SceneOptimizer
  94636. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94637. */
  94638. var SceneOptimization = /** @class */ (function () {
  94639. /**
  94640. * Creates the SceneOptimization object
  94641. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94642. * @param desc defines the description associated with the optimization
  94643. */
  94644. function SceneOptimization(
  94645. /**
  94646. * Defines the priority of this optimization (0 by default which means first in the list)
  94647. */
  94648. priority) {
  94649. if (priority === void 0) { priority = 0; }
  94650. this.priority = priority;
  94651. }
  94652. /**
  94653. * Gets a string describing the action executed by the current optimization
  94654. * @returns description string
  94655. */
  94656. SceneOptimization.prototype.getDescription = function () {
  94657. return "";
  94658. };
  94659. /**
  94660. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94661. * @param scene defines the current scene where to apply this optimization
  94662. * @param optimizer defines the current optimizer
  94663. * @returns true if everything that can be done was applied
  94664. */
  94665. SceneOptimization.prototype.apply = function (scene, optimizer) {
  94666. return true;
  94667. };
  94668. ;
  94669. return SceneOptimization;
  94670. }());
  94671. BABYLON.SceneOptimization = SceneOptimization;
  94672. /**
  94673. * Defines an optimization used to reduce the size of render target textures
  94674. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94675. */
  94676. var TextureOptimization = /** @class */ (function (_super) {
  94677. __extends(TextureOptimization, _super);
  94678. /**
  94679. * Creates the TextureOptimization object
  94680. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94681. * @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
  94682. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94683. */
  94684. function TextureOptimization(
  94685. /**
  94686. * Defines the priority of this optimization (0 by default which means first in the list)
  94687. */
  94688. priority,
  94689. /**
  94690. * 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
  94691. */
  94692. maximumSize,
  94693. /**
  94694. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94695. */
  94696. step) {
  94697. if (priority === void 0) { priority = 0; }
  94698. if (maximumSize === void 0) { maximumSize = 1024; }
  94699. if (step === void 0) { step = 0.5; }
  94700. var _this = _super.call(this, priority) || this;
  94701. _this.priority = priority;
  94702. _this.maximumSize = maximumSize;
  94703. _this.step = step;
  94704. return _this;
  94705. }
  94706. /**
  94707. * Gets a string describing the action executed by the current optimization
  94708. * @returns description string
  94709. */
  94710. TextureOptimization.prototype.getDescription = function () {
  94711. return "Reducing render target texture size to " + this.maximumSize;
  94712. };
  94713. /**
  94714. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94715. * @param scene defines the current scene where to apply this optimization
  94716. * @param optimizer defines the current optimizer
  94717. * @returns true if everything that can be done was applied
  94718. */
  94719. TextureOptimization.prototype.apply = function (scene, optimizer) {
  94720. var allDone = true;
  94721. for (var index = 0; index < scene.textures.length; index++) {
  94722. var texture = scene.textures[index];
  94723. if (!texture.canRescale || texture.getContext) {
  94724. continue;
  94725. }
  94726. var currentSize = texture.getSize();
  94727. var maxDimension = Math.max(currentSize.width, currentSize.height);
  94728. if (maxDimension > this.maximumSize) {
  94729. texture.scale(this.step);
  94730. allDone = false;
  94731. }
  94732. }
  94733. return allDone;
  94734. };
  94735. return TextureOptimization;
  94736. }(SceneOptimization));
  94737. BABYLON.TextureOptimization = TextureOptimization;
  94738. /**
  94739. * Defines an optimization used to increase or decrease the rendering resolution
  94740. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94741. */
  94742. var HardwareScalingOptimization = /** @class */ (function (_super) {
  94743. __extends(HardwareScalingOptimization, _super);
  94744. /**
  94745. * Creates the HardwareScalingOptimization object
  94746. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94747. * @param maximumScale defines the maximum scale to use (2 by default)
  94748. * @param step defines the step to use between two passes (0.5 by default)
  94749. */
  94750. function HardwareScalingOptimization(
  94751. /**
  94752. * Defines the priority of this optimization (0 by default which means first in the list)
  94753. */
  94754. priority,
  94755. /**
  94756. * Defines the maximum scale to use (2 by default)
  94757. */
  94758. maximumScale,
  94759. /**
  94760. * Defines the step to use between two passes (0.5 by default)
  94761. */
  94762. step) {
  94763. if (priority === void 0) { priority = 0; }
  94764. if (maximumScale === void 0) { maximumScale = 2; }
  94765. if (step === void 0) { step = 0.25; }
  94766. var _this = _super.call(this, priority) || this;
  94767. _this.priority = priority;
  94768. _this.maximumScale = maximumScale;
  94769. _this.step = step;
  94770. _this._currentScale = -1;
  94771. _this._directionOffset = 1;
  94772. return _this;
  94773. }
  94774. /**
  94775. * Gets a string describing the action executed by the current optimization
  94776. * @return description string
  94777. */
  94778. HardwareScalingOptimization.prototype.getDescription = function () {
  94779. return "Setting hardware scaling level to " + this._currentScale;
  94780. };
  94781. /**
  94782. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94783. * @param scene defines the current scene where to apply this optimization
  94784. * @param optimizer defines the current optimizer
  94785. * @returns true if everything that can be done was applied
  94786. */
  94787. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  94788. if (this._currentScale === -1) {
  94789. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  94790. if (this._currentScale > this.maximumScale) {
  94791. this._directionOffset = -1;
  94792. }
  94793. }
  94794. this._currentScale += this._directionOffset * this.step;
  94795. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  94796. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  94797. };
  94798. ;
  94799. return HardwareScalingOptimization;
  94800. }(SceneOptimization));
  94801. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  94802. /**
  94803. * Defines an optimization used to remove shadows
  94804. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94805. */
  94806. var ShadowsOptimization = /** @class */ (function (_super) {
  94807. __extends(ShadowsOptimization, _super);
  94808. function ShadowsOptimization() {
  94809. return _super !== null && _super.apply(this, arguments) || this;
  94810. }
  94811. /**
  94812. * Gets a string describing the action executed by the current optimization
  94813. * @return description string
  94814. */
  94815. ShadowsOptimization.prototype.getDescription = function () {
  94816. return "Turning shadows on/off";
  94817. };
  94818. /**
  94819. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94820. * @param scene defines the current scene where to apply this optimization
  94821. * @param optimizer defines the current optimizer
  94822. * @returns true if everything that can be done was applied
  94823. */
  94824. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  94825. scene.shadowsEnabled = optimizer.isInImprovementMode;
  94826. return true;
  94827. };
  94828. ;
  94829. return ShadowsOptimization;
  94830. }(SceneOptimization));
  94831. BABYLON.ShadowsOptimization = ShadowsOptimization;
  94832. /**
  94833. * Defines an optimization used to turn post-processes off
  94834. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94835. */
  94836. var PostProcessesOptimization = /** @class */ (function (_super) {
  94837. __extends(PostProcessesOptimization, _super);
  94838. function PostProcessesOptimization() {
  94839. return _super !== null && _super.apply(this, arguments) || this;
  94840. }
  94841. /**
  94842. * Gets a string describing the action executed by the current optimization
  94843. * @return description string
  94844. */
  94845. PostProcessesOptimization.prototype.getDescription = function () {
  94846. return "Turning post-processes on/off";
  94847. };
  94848. /**
  94849. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94850. * @param scene defines the current scene where to apply this optimization
  94851. * @param optimizer defines the current optimizer
  94852. * @returns true if everything that can be done was applied
  94853. */
  94854. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  94855. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  94856. return true;
  94857. };
  94858. ;
  94859. return PostProcessesOptimization;
  94860. }(SceneOptimization));
  94861. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  94862. /**
  94863. * Defines an optimization used to turn lens flares off
  94864. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94865. */
  94866. var LensFlaresOptimization = /** @class */ (function (_super) {
  94867. __extends(LensFlaresOptimization, _super);
  94868. function LensFlaresOptimization() {
  94869. return _super !== null && _super.apply(this, arguments) || this;
  94870. }
  94871. /**
  94872. * Gets a string describing the action executed by the current optimization
  94873. * @return description string
  94874. */
  94875. LensFlaresOptimization.prototype.getDescription = function () {
  94876. return "Turning lens flares on/off";
  94877. };
  94878. /**
  94879. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94880. * @param scene defines the current scene where to apply this optimization
  94881. * @param optimizer defines the current optimizer
  94882. * @returns true if everything that can be done was applied
  94883. */
  94884. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  94885. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  94886. return true;
  94887. };
  94888. ;
  94889. return LensFlaresOptimization;
  94890. }(SceneOptimization));
  94891. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  94892. /**
  94893. * Defines an optimization based on user defined callback.
  94894. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94895. */
  94896. var CustomOptimization = /** @class */ (function (_super) {
  94897. __extends(CustomOptimization, _super);
  94898. function CustomOptimization() {
  94899. return _super !== null && _super.apply(this, arguments) || this;
  94900. }
  94901. /**
  94902. * Gets a string describing the action executed by the current optimization
  94903. * @returns description string
  94904. */
  94905. CustomOptimization.prototype.getDescription = function () {
  94906. if (this.onGetDescription) {
  94907. return this.onGetDescription();
  94908. }
  94909. return "Running user defined callback";
  94910. };
  94911. /**
  94912. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94913. * @param scene defines the current scene where to apply this optimization
  94914. * @param optimizer defines the current optimizer
  94915. * @returns true if everything that can be done was applied
  94916. */
  94917. CustomOptimization.prototype.apply = function (scene, optimizer) {
  94918. if (this.onApply) {
  94919. return this.onApply(scene, optimizer);
  94920. }
  94921. return true;
  94922. };
  94923. ;
  94924. return CustomOptimization;
  94925. }(SceneOptimization));
  94926. BABYLON.CustomOptimization = CustomOptimization;
  94927. /**
  94928. * Defines an optimization used to turn particles off
  94929. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94930. */
  94931. var ParticlesOptimization = /** @class */ (function (_super) {
  94932. __extends(ParticlesOptimization, _super);
  94933. function ParticlesOptimization() {
  94934. return _super !== null && _super.apply(this, arguments) || this;
  94935. }
  94936. /**
  94937. * Gets a string describing the action executed by the current optimization
  94938. * @return description string
  94939. */
  94940. ParticlesOptimization.prototype.getDescription = function () {
  94941. return "Turning particles on/off";
  94942. };
  94943. /**
  94944. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94945. * @param scene defines the current scene where to apply this optimization
  94946. * @param optimizer defines the current optimizer
  94947. * @returns true if everything that can be done was applied
  94948. */
  94949. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  94950. scene.particlesEnabled = optimizer.isInImprovementMode;
  94951. return true;
  94952. };
  94953. ;
  94954. return ParticlesOptimization;
  94955. }(SceneOptimization));
  94956. BABYLON.ParticlesOptimization = ParticlesOptimization;
  94957. /**
  94958. * Defines an optimization used to turn render targets off
  94959. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94960. */
  94961. var RenderTargetsOptimization = /** @class */ (function (_super) {
  94962. __extends(RenderTargetsOptimization, _super);
  94963. function RenderTargetsOptimization() {
  94964. return _super !== null && _super.apply(this, arguments) || this;
  94965. }
  94966. /**
  94967. * Gets a string describing the action executed by the current optimization
  94968. * @return description string
  94969. */
  94970. RenderTargetsOptimization.prototype.getDescription = function () {
  94971. return "Turning render targets off";
  94972. };
  94973. /**
  94974. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94975. * @param scene defines the current scene where to apply this optimization
  94976. * @param optimizer defines the current optimizer
  94977. * @returns true if everything that can be done was applied
  94978. */
  94979. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  94980. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  94981. return true;
  94982. };
  94983. ;
  94984. return RenderTargetsOptimization;
  94985. }(SceneOptimization));
  94986. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  94987. /**
  94988. * Defines an optimization used to merge meshes with compatible materials
  94989. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94990. */
  94991. var MergeMeshesOptimization = /** @class */ (function (_super) {
  94992. __extends(MergeMeshesOptimization, _super);
  94993. function MergeMeshesOptimization() {
  94994. var _this = _super !== null && _super.apply(this, arguments) || this;
  94995. _this._canBeMerged = function (abstractMesh) {
  94996. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  94997. return false;
  94998. }
  94999. var mesh = abstractMesh;
  95000. if (!mesh.isVisible || !mesh.isEnabled()) {
  95001. return false;
  95002. }
  95003. if (mesh.instances.length > 0) {
  95004. return false;
  95005. }
  95006. if (mesh.skeleton || mesh.hasLODLevels) {
  95007. return false;
  95008. }
  95009. if (mesh.parent) {
  95010. return false;
  95011. }
  95012. return true;
  95013. };
  95014. return _this;
  95015. }
  95016. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  95017. /**
  95018. * Gets or sets a boolean which defines if optimization octree has to be updated
  95019. */
  95020. get: function () {
  95021. return MergeMeshesOptimization._UpdateSelectionTree;
  95022. },
  95023. /**
  95024. * Gets or sets a boolean which defines if optimization octree has to be updated
  95025. */
  95026. set: function (value) {
  95027. MergeMeshesOptimization._UpdateSelectionTree = value;
  95028. },
  95029. enumerable: true,
  95030. configurable: true
  95031. });
  95032. /**
  95033. * Gets a string describing the action executed by the current optimization
  95034. * @return description string
  95035. */
  95036. MergeMeshesOptimization.prototype.getDescription = function () {
  95037. return "Merging similar meshes together";
  95038. };
  95039. /**
  95040. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  95041. * @param scene defines the current scene where to apply this optimization
  95042. * @param optimizer defines the current optimizer
  95043. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  95044. * @returns true if everything that can be done was applied
  95045. */
  95046. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  95047. var globalPool = scene.meshes.slice(0);
  95048. var globalLength = globalPool.length;
  95049. for (var index = 0; index < globalLength; index++) {
  95050. var currentPool = new Array();
  95051. var current = globalPool[index];
  95052. // Checks
  95053. if (!this._canBeMerged(current)) {
  95054. continue;
  95055. }
  95056. currentPool.push(current);
  95057. // Find compatible meshes
  95058. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  95059. var otherMesh = globalPool[subIndex];
  95060. if (!this._canBeMerged(otherMesh)) {
  95061. continue;
  95062. }
  95063. if (otherMesh.material !== current.material) {
  95064. continue;
  95065. }
  95066. if (otherMesh.checkCollisions !== current.checkCollisions) {
  95067. continue;
  95068. }
  95069. currentPool.push(otherMesh);
  95070. globalLength--;
  95071. globalPool.splice(subIndex, 1);
  95072. subIndex--;
  95073. }
  95074. if (currentPool.length < 2) {
  95075. continue;
  95076. }
  95077. // Merge meshes
  95078. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  95079. }
  95080. if (updateSelectionTree != undefined) {
  95081. if (updateSelectionTree) {
  95082. scene.createOrUpdateSelectionOctree();
  95083. }
  95084. }
  95085. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  95086. scene.createOrUpdateSelectionOctree();
  95087. }
  95088. return true;
  95089. };
  95090. ;
  95091. MergeMeshesOptimization._UpdateSelectionTree = false;
  95092. return MergeMeshesOptimization;
  95093. }(SceneOptimization));
  95094. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  95095. /**
  95096. * Defines a list of options used by SceneOptimizer
  95097. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95098. */
  95099. var SceneOptimizerOptions = /** @class */ (function () {
  95100. /**
  95101. * Creates a new list of options used by SceneOptimizer
  95102. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  95103. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  95104. */
  95105. function SceneOptimizerOptions(
  95106. /**
  95107. * Defines the target frame rate to reach (60 by default)
  95108. */
  95109. targetFrameRate,
  95110. /**
  95111. * Defines the interval between two checkes (2000ms by default)
  95112. */
  95113. trackerDuration) {
  95114. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  95115. if (trackerDuration === void 0) { trackerDuration = 2000; }
  95116. this.targetFrameRate = targetFrameRate;
  95117. this.trackerDuration = trackerDuration;
  95118. /**
  95119. * Gets the list of optimizations to apply
  95120. */
  95121. this.optimizations = new Array();
  95122. }
  95123. /**
  95124. * Add a new optimization
  95125. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  95126. * @returns the current SceneOptimizerOptions
  95127. */
  95128. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  95129. this.optimizations.push(optimization);
  95130. return this;
  95131. };
  95132. /**
  95133. * Add a new custom optimization
  95134. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  95135. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  95136. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95137. * @returns the current SceneOptimizerOptions
  95138. */
  95139. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  95140. if (priority === void 0) { priority = 0; }
  95141. var optimization = new CustomOptimization(priority);
  95142. optimization.onApply = onApply;
  95143. optimization.onGetDescription = onGetDescription;
  95144. this.optimizations.push(optimization);
  95145. return this;
  95146. };
  95147. /**
  95148. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95149. * @param targetFrameRate defines the target frame rate (60 by default)
  95150. * @returns a SceneOptimizerOptions object
  95151. */
  95152. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95153. var result = new SceneOptimizerOptions(targetFrameRate);
  95154. var priority = 0;
  95155. result.addOptimization(new MergeMeshesOptimization(priority));
  95156. result.addOptimization(new ShadowsOptimization(priority));
  95157. result.addOptimization(new LensFlaresOptimization(priority));
  95158. // Next priority
  95159. priority++;
  95160. result.addOptimization(new PostProcessesOptimization(priority));
  95161. result.addOptimization(new ParticlesOptimization(priority));
  95162. // Next priority
  95163. priority++;
  95164. result.addOptimization(new TextureOptimization(priority, 1024));
  95165. return result;
  95166. };
  95167. /**
  95168. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95169. * @param targetFrameRate defines the target frame rate (60 by default)
  95170. * @returns a SceneOptimizerOptions object
  95171. */
  95172. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95173. var result = new SceneOptimizerOptions(targetFrameRate);
  95174. var priority = 0;
  95175. result.addOptimization(new MergeMeshesOptimization(priority));
  95176. result.addOptimization(new ShadowsOptimization(priority));
  95177. result.addOptimization(new LensFlaresOptimization(priority));
  95178. // Next priority
  95179. priority++;
  95180. result.addOptimization(new PostProcessesOptimization(priority));
  95181. result.addOptimization(new ParticlesOptimization(priority));
  95182. // Next priority
  95183. priority++;
  95184. result.addOptimization(new TextureOptimization(priority, 512));
  95185. // Next priority
  95186. priority++;
  95187. result.addOptimization(new RenderTargetsOptimization(priority));
  95188. // Next priority
  95189. priority++;
  95190. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95191. return result;
  95192. };
  95193. /**
  95194. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95195. * @param targetFrameRate defines the target frame rate (60 by default)
  95196. * @returns a SceneOptimizerOptions object
  95197. */
  95198. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95199. var result = new SceneOptimizerOptions(targetFrameRate);
  95200. var priority = 0;
  95201. result.addOptimization(new MergeMeshesOptimization(priority));
  95202. result.addOptimization(new ShadowsOptimization(priority));
  95203. result.addOptimization(new LensFlaresOptimization(priority));
  95204. // Next priority
  95205. priority++;
  95206. result.addOptimization(new PostProcessesOptimization(priority));
  95207. result.addOptimization(new ParticlesOptimization(priority));
  95208. // Next priority
  95209. priority++;
  95210. result.addOptimization(new TextureOptimization(priority, 256));
  95211. // Next priority
  95212. priority++;
  95213. result.addOptimization(new RenderTargetsOptimization(priority));
  95214. // Next priority
  95215. priority++;
  95216. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  95217. return result;
  95218. };
  95219. return SceneOptimizerOptions;
  95220. }());
  95221. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  95222. /**
  95223. * Class used to run optimizations in order to reach a target frame rate
  95224. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95225. */
  95226. var SceneOptimizer = /** @class */ (function () {
  95227. /**
  95228. * Creates a new SceneOptimizer
  95229. * @param scene defines the scene to work on
  95230. * @param options defines the options to use with the SceneOptimizer
  95231. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  95232. * @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)
  95233. */
  95234. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  95235. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  95236. if (improvementMode === void 0) { improvementMode = false; }
  95237. var _this = this;
  95238. this._isRunning = false;
  95239. this._currentPriorityLevel = 0;
  95240. this._targetFrameRate = 60;
  95241. this._trackerDuration = 2000;
  95242. this._currentFrameRate = 0;
  95243. this._improvementMode = false;
  95244. /**
  95245. * Defines an observable called when the optimizer reaches the target frame rate
  95246. */
  95247. this.onSuccessObservable = new BABYLON.Observable();
  95248. /**
  95249. * Defines an observable called when the optimizer enables an optimization
  95250. */
  95251. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  95252. /**
  95253. * Defines an observable called when the optimizer is not able to reach the target frame rate
  95254. */
  95255. this.onFailureObservable = new BABYLON.Observable();
  95256. if (!options) {
  95257. this._options = new SceneOptimizerOptions();
  95258. }
  95259. else {
  95260. this._options = options;
  95261. }
  95262. if (this._options.targetFrameRate) {
  95263. this._targetFrameRate = this._options.targetFrameRate;
  95264. }
  95265. if (this._options.trackerDuration) {
  95266. this._trackerDuration = this._options.trackerDuration;
  95267. }
  95268. if (autoGeneratePriorities) {
  95269. var priority = 0;
  95270. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  95271. var optim = _a[_i];
  95272. optim.priority = priority++;
  95273. }
  95274. }
  95275. this._improvementMode = improvementMode;
  95276. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95277. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  95278. _this._sceneDisposeObserver = null;
  95279. _this.dispose();
  95280. });
  95281. }
  95282. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  95283. /**
  95284. * Gets a boolean indicating if the optimizer is in improvement mode
  95285. */
  95286. get: function () {
  95287. return this._improvementMode;
  95288. },
  95289. enumerable: true,
  95290. configurable: true
  95291. });
  95292. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95293. /**
  95294. * Gets the current priority level (0 at start)
  95295. */
  95296. get: function () {
  95297. return this._currentPriorityLevel;
  95298. },
  95299. enumerable: true,
  95300. configurable: true
  95301. });
  95302. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  95303. /**
  95304. * Gets the current frame rate checked by the SceneOptimizer
  95305. */
  95306. get: function () {
  95307. return this._currentFrameRate;
  95308. },
  95309. enumerable: true,
  95310. configurable: true
  95311. });
  95312. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  95313. /**
  95314. * Gets or sets the current target frame rate (60 by default)
  95315. */
  95316. get: function () {
  95317. return this._targetFrameRate;
  95318. },
  95319. /**
  95320. * Gets or sets the current target frame rate (60 by default)
  95321. */
  95322. set: function (value) {
  95323. this._targetFrameRate = value;
  95324. },
  95325. enumerable: true,
  95326. configurable: true
  95327. });
  95328. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  95329. /**
  95330. * Gets or sets the current interval between two checks (every 2000ms by default)
  95331. */
  95332. get: function () {
  95333. return this._trackerDuration;
  95334. },
  95335. /**
  95336. * Gets or sets the current interval between two checks (every 2000ms by default)
  95337. */
  95338. set: function (value) {
  95339. this._trackerDuration = value;
  95340. },
  95341. enumerable: true,
  95342. configurable: true
  95343. });
  95344. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  95345. /**
  95346. * Gets the list of active optimizations
  95347. */
  95348. get: function () {
  95349. return this._options.optimizations;
  95350. },
  95351. enumerable: true,
  95352. configurable: true
  95353. });
  95354. /**
  95355. * Stops the current optimizer
  95356. */
  95357. SceneOptimizer.prototype.stop = function () {
  95358. this._isRunning = false;
  95359. };
  95360. /**
  95361. * Reset the optimizer to initial step (current priority level = 0)
  95362. */
  95363. SceneOptimizer.prototype.reset = function () {
  95364. this._currentPriorityLevel = 0;
  95365. };
  95366. /**
  95367. * Start the optimizer. By default it will try to reach a specific framerate
  95368. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  95369. */
  95370. SceneOptimizer.prototype.start = function () {
  95371. var _this = this;
  95372. if (this._isRunning) {
  95373. return;
  95374. }
  95375. this._isRunning = true;
  95376. // Let's wait for the scene to be ready before running our check
  95377. this._scene.executeWhenReady(function () {
  95378. setTimeout(function () {
  95379. _this._checkCurrentState();
  95380. }, _this._trackerDuration);
  95381. });
  95382. };
  95383. SceneOptimizer.prototype._checkCurrentState = function () {
  95384. var _this = this;
  95385. if (!this._isRunning) {
  95386. return;
  95387. }
  95388. var scene = this._scene;
  95389. var options = this._options;
  95390. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  95391. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  95392. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  95393. this._isRunning = false;
  95394. this.onSuccessObservable.notifyObservers(this);
  95395. return;
  95396. }
  95397. // Apply current level of optimizations
  95398. var allDone = true;
  95399. var noOptimizationApplied = true;
  95400. for (var index = 0; index < options.optimizations.length; index++) {
  95401. var optimization = options.optimizations[index];
  95402. if (optimization.priority === this._currentPriorityLevel) {
  95403. noOptimizationApplied = false;
  95404. allDone = allDone && optimization.apply(scene, this);
  95405. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  95406. }
  95407. }
  95408. // If no optimization was applied, this is a failure :(
  95409. if (noOptimizationApplied) {
  95410. this._isRunning = false;
  95411. this.onFailureObservable.notifyObservers(this);
  95412. return;
  95413. }
  95414. // If all optimizations were done, move to next level
  95415. if (allDone) {
  95416. this._currentPriorityLevel++;
  95417. }
  95418. // Let's the system running for a specific amount of time before checking FPS
  95419. scene.executeWhenReady(function () {
  95420. setTimeout(function () {
  95421. _this._checkCurrentState();
  95422. }, _this._trackerDuration);
  95423. });
  95424. };
  95425. /**
  95426. * Release all resources
  95427. */
  95428. SceneOptimizer.prototype.dispose = function () {
  95429. this.stop();
  95430. this.onSuccessObservable.clear();
  95431. this.onFailureObservable.clear();
  95432. this.onNewOptimizationAppliedObservable.clear();
  95433. if (this._sceneDisposeObserver) {
  95434. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95435. }
  95436. };
  95437. /**
  95438. * Helper function to create a SceneOptimizer with one single line of code
  95439. * @param scene defines the scene to work on
  95440. * @param options defines the options to use with the SceneOptimizer
  95441. * @param onSuccess defines a callback to call on success
  95442. * @param onFailure defines a callback to call on failure
  95443. * @returns the new SceneOptimizer object
  95444. */
  95445. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95446. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95447. if (onSuccess) {
  95448. optimizer.onSuccessObservable.add(function () {
  95449. onSuccess();
  95450. });
  95451. }
  95452. if (onFailure) {
  95453. optimizer.onFailureObservable.add(function () {
  95454. onFailure();
  95455. });
  95456. }
  95457. optimizer.start();
  95458. return optimizer;
  95459. };
  95460. return SceneOptimizer;
  95461. }());
  95462. BABYLON.SceneOptimizer = SceneOptimizer;
  95463. })(BABYLON || (BABYLON = {}));
  95464. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95465. var BABYLON;
  95466. (function (BABYLON) {
  95467. var OutlineRenderer = /** @class */ (function () {
  95468. function OutlineRenderer(scene) {
  95469. this.zOffset = 1;
  95470. this._scene = scene;
  95471. }
  95472. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95473. var _this = this;
  95474. if (useOverlay === void 0) { useOverlay = false; }
  95475. var scene = this._scene;
  95476. var engine = this._scene.getEngine();
  95477. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95478. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95479. return;
  95480. }
  95481. var mesh = subMesh.getRenderingMesh();
  95482. var material = subMesh.getMaterial();
  95483. if (!material || !scene.activeCamera) {
  95484. return;
  95485. }
  95486. engine.enableEffect(this._effect);
  95487. // Logarithmic depth
  95488. if (material.useLogarithmicDepth) {
  95489. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95490. }
  95491. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95492. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95493. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95494. // Bones
  95495. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95496. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95497. }
  95498. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  95499. // Alpha test
  95500. if (material && material.needAlphaTesting()) {
  95501. var alphaTexture = material.getAlphaTestTexture();
  95502. if (alphaTexture) {
  95503. this._effect.setTexture("diffuseSampler", alphaTexture);
  95504. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  95505. }
  95506. }
  95507. engine.setZOffset(-this.zOffset);
  95508. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  95509. engine.setZOffset(0);
  95510. };
  95511. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  95512. var defines = [];
  95513. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  95514. var mesh = subMesh.getMesh();
  95515. var material = subMesh.getMaterial();
  95516. if (material) {
  95517. // Alpha test
  95518. if (material.needAlphaTesting()) {
  95519. defines.push("#define ALPHATEST");
  95520. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95521. attribs.push(BABYLON.VertexBuffer.UVKind);
  95522. defines.push("#define UV1");
  95523. }
  95524. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  95525. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95526. defines.push("#define UV2");
  95527. }
  95528. }
  95529. //Logarithmic depth
  95530. if (material.useLogarithmicDepth) {
  95531. defines.push("#define LOGARITHMICDEPTH");
  95532. }
  95533. }
  95534. // Bones
  95535. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95536. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95537. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95538. if (mesh.numBoneInfluencers > 4) {
  95539. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95540. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95541. }
  95542. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95543. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  95544. }
  95545. else {
  95546. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95547. }
  95548. // Instances
  95549. if (useInstances) {
  95550. defines.push("#define INSTANCES");
  95551. attribs.push("world0");
  95552. attribs.push("world1");
  95553. attribs.push("world2");
  95554. attribs.push("world3");
  95555. }
  95556. // Get correct effect
  95557. var join = defines.join("\n");
  95558. if (this._cachedDefines !== join) {
  95559. this._cachedDefines = join;
  95560. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  95561. }
  95562. return this._effect.isReady();
  95563. };
  95564. return OutlineRenderer;
  95565. }());
  95566. BABYLON.OutlineRenderer = OutlineRenderer;
  95567. })(BABYLON || (BABYLON = {}));
  95568. //# sourceMappingURL=babylon.outlineRenderer.js.map
  95569. var BABYLON;
  95570. (function (BABYLON) {
  95571. var FaceAdjacencies = /** @class */ (function () {
  95572. function FaceAdjacencies() {
  95573. this.edges = new Array();
  95574. this.edgesConnectedCount = 0;
  95575. }
  95576. return FaceAdjacencies;
  95577. }());
  95578. var EdgesRenderer = /** @class */ (function () {
  95579. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  95580. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  95581. if (epsilon === void 0) { epsilon = 0.95; }
  95582. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  95583. this.edgesWidthScalerForOrthographic = 1000.0;
  95584. this.edgesWidthScalerForPerspective = 50.0;
  95585. this._linesPositions = new Array();
  95586. this._linesNormals = new Array();
  95587. this._linesIndices = new Array();
  95588. this._buffers = {};
  95589. this._checkVerticesInsteadOfIndices = false;
  95590. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  95591. this.isEnabled = true;
  95592. this._source = source;
  95593. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  95594. this._epsilon = epsilon;
  95595. this._prepareRessources();
  95596. this._generateEdgesLines();
  95597. }
  95598. EdgesRenderer.prototype._prepareRessources = function () {
  95599. if (this._lineShader) {
  95600. return;
  95601. }
  95602. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  95603. attributes: ["position", "normal"],
  95604. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  95605. });
  95606. this._lineShader.disableDepthWrite = true;
  95607. this._lineShader.backFaceCulling = false;
  95608. };
  95609. EdgesRenderer.prototype._rebuild = function () {
  95610. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95611. if (buffer) {
  95612. buffer._rebuild();
  95613. }
  95614. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95615. if (buffer) {
  95616. buffer._rebuild();
  95617. }
  95618. var scene = this._source.getScene();
  95619. var engine = scene.getEngine();
  95620. this._ib = engine.createIndexBuffer(this._linesIndices);
  95621. };
  95622. EdgesRenderer.prototype.dispose = function () {
  95623. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95624. if (buffer) {
  95625. buffer.dispose();
  95626. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  95627. }
  95628. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95629. if (buffer) {
  95630. buffer.dispose();
  95631. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  95632. }
  95633. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  95634. this._lineShader.dispose();
  95635. };
  95636. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  95637. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  95638. return 0;
  95639. }
  95640. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  95641. return 1;
  95642. }
  95643. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  95644. return 2;
  95645. }
  95646. return -1;
  95647. };
  95648. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  95649. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  95650. return 0;
  95651. }
  95652. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  95653. return 1;
  95654. }
  95655. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  95656. return 2;
  95657. }
  95658. return -1;
  95659. };
  95660. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  95661. var needToCreateLine;
  95662. if (edge === undefined) {
  95663. needToCreateLine = true;
  95664. }
  95665. else {
  95666. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  95667. needToCreateLine = dotProduct < this._epsilon;
  95668. }
  95669. if (needToCreateLine) {
  95670. var offset = this._linesPositions.length / 3;
  95671. var normal = p0.subtract(p1);
  95672. normal.normalize();
  95673. // Positions
  95674. this._linesPositions.push(p0.x);
  95675. this._linesPositions.push(p0.y);
  95676. this._linesPositions.push(p0.z);
  95677. this._linesPositions.push(p0.x);
  95678. this._linesPositions.push(p0.y);
  95679. this._linesPositions.push(p0.z);
  95680. this._linesPositions.push(p1.x);
  95681. this._linesPositions.push(p1.y);
  95682. this._linesPositions.push(p1.z);
  95683. this._linesPositions.push(p1.x);
  95684. this._linesPositions.push(p1.y);
  95685. this._linesPositions.push(p1.z);
  95686. // Normals
  95687. this._linesNormals.push(p1.x);
  95688. this._linesNormals.push(p1.y);
  95689. this._linesNormals.push(p1.z);
  95690. this._linesNormals.push(-1);
  95691. this._linesNormals.push(p1.x);
  95692. this._linesNormals.push(p1.y);
  95693. this._linesNormals.push(p1.z);
  95694. this._linesNormals.push(1);
  95695. this._linesNormals.push(p0.x);
  95696. this._linesNormals.push(p0.y);
  95697. this._linesNormals.push(p0.z);
  95698. this._linesNormals.push(-1);
  95699. this._linesNormals.push(p0.x);
  95700. this._linesNormals.push(p0.y);
  95701. this._linesNormals.push(p0.z);
  95702. this._linesNormals.push(1);
  95703. // Indices
  95704. this._linesIndices.push(offset);
  95705. this._linesIndices.push(offset + 1);
  95706. this._linesIndices.push(offset + 2);
  95707. this._linesIndices.push(offset);
  95708. this._linesIndices.push(offset + 2);
  95709. this._linesIndices.push(offset + 3);
  95710. }
  95711. };
  95712. EdgesRenderer.prototype._generateEdgesLines = function () {
  95713. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95714. var indices = this._source.getIndices();
  95715. if (!indices || !positions) {
  95716. return;
  95717. }
  95718. // First let's find adjacencies
  95719. var adjacencies = new Array();
  95720. var faceNormals = new Array();
  95721. var index;
  95722. var faceAdjacencies;
  95723. // Prepare faces
  95724. for (index = 0; index < indices.length; index += 3) {
  95725. faceAdjacencies = new FaceAdjacencies();
  95726. var p0Index = indices[index];
  95727. var p1Index = indices[index + 1];
  95728. var p2Index = indices[index + 2];
  95729. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  95730. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  95731. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  95732. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  95733. faceNormal.normalize();
  95734. faceNormals.push(faceNormal);
  95735. adjacencies.push(faceAdjacencies);
  95736. }
  95737. // Scan
  95738. for (index = 0; index < adjacencies.length; index++) {
  95739. faceAdjacencies = adjacencies[index];
  95740. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  95741. var otherFaceAdjacencies = adjacencies[otherIndex];
  95742. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  95743. break;
  95744. }
  95745. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  95746. continue;
  95747. }
  95748. var otherP0 = indices[otherIndex * 3];
  95749. var otherP1 = indices[otherIndex * 3 + 1];
  95750. var otherP2 = indices[otherIndex * 3 + 2];
  95751. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  95752. var otherEdgeIndex = 0;
  95753. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  95754. continue;
  95755. }
  95756. switch (edgeIndex) {
  95757. case 0:
  95758. if (this._checkVerticesInsteadOfIndices) {
  95759. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95760. }
  95761. else {
  95762. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  95763. }
  95764. break;
  95765. case 1:
  95766. if (this._checkVerticesInsteadOfIndices) {
  95767. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95768. }
  95769. else {
  95770. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  95771. }
  95772. break;
  95773. case 2:
  95774. if (this._checkVerticesInsteadOfIndices) {
  95775. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95776. }
  95777. else {
  95778. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  95779. }
  95780. break;
  95781. }
  95782. if (otherEdgeIndex === -1) {
  95783. continue;
  95784. }
  95785. faceAdjacencies.edges[edgeIndex] = otherIndex;
  95786. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  95787. faceAdjacencies.edgesConnectedCount++;
  95788. otherFaceAdjacencies.edgesConnectedCount++;
  95789. if (faceAdjacencies.edgesConnectedCount === 3) {
  95790. break;
  95791. }
  95792. }
  95793. }
  95794. }
  95795. // Create lines
  95796. for (index = 0; index < adjacencies.length; index++) {
  95797. // 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
  95798. var current = adjacencies[index];
  95799. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  95800. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  95801. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  95802. }
  95803. // Merge into a single mesh
  95804. var engine = this._source.getScene().getEngine();
  95805. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  95806. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  95807. this._ib = engine.createIndexBuffer(this._linesIndices);
  95808. this._indicesCount = this._linesIndices.length;
  95809. };
  95810. EdgesRenderer.prototype.render = function () {
  95811. var scene = this._source.getScene();
  95812. if (!this._lineShader.isReady() || !scene.activeCamera) {
  95813. return;
  95814. }
  95815. var engine = scene.getEngine();
  95816. this._lineShader._preBind();
  95817. // VBOs
  95818. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  95819. scene.resetCachedMaterial();
  95820. this._lineShader.setColor4("color", this._source.edgesColor);
  95821. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  95822. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  95823. }
  95824. else {
  95825. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  95826. }
  95827. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  95828. this._lineShader.bind(this._source.getWorldMatrix());
  95829. // Draw order
  95830. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  95831. this._lineShader.unbind();
  95832. engine.setDepthWrite(true);
  95833. };
  95834. return EdgesRenderer;
  95835. }());
  95836. BABYLON.EdgesRenderer = EdgesRenderer;
  95837. })(BABYLON || (BABYLON = {}));
  95838. //# sourceMappingURL=babylon.edgesRenderer.js.map
  95839. var BABYLON;
  95840. (function (BABYLON) {
  95841. // Adds the parser to the scene parsers.
  95842. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  95843. if (parsedData.effectLayers) {
  95844. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  95845. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  95846. container.effectLayers.push(effectLayer);
  95847. }
  95848. }
  95849. });
  95850. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  95851. var index = this.effectLayers.indexOf(toRemove);
  95852. if (index !== -1) {
  95853. this.effectLayers.splice(index, 1);
  95854. }
  95855. return index;
  95856. };
  95857. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  95858. this.effectLayers.push(newEffectLayer);
  95859. };
  95860. /**
  95861. * Defines the layer scene component responsible to manage any effect layers
  95862. * in a given scene.
  95863. */
  95864. var EffectLayerSceneComponent = /** @class */ (function () {
  95865. /**
  95866. * Creates a new instance of the component for the given scene
  95867. * @param scene Defines the scene to register the component in
  95868. */
  95869. function EffectLayerSceneComponent(scene) {
  95870. /**
  95871. * The component name helpfull to identify the component in the list of scene components.
  95872. */
  95873. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  95874. this._renderEffects = false;
  95875. this._needStencil = false;
  95876. this._previousStencilState = false;
  95877. this.scene = scene;
  95878. this._engine = scene.getEngine();
  95879. this._effectLayers = scene.effectLayers = new Array();
  95880. }
  95881. /**
  95882. * Registers the component in a given scene
  95883. */
  95884. EffectLayerSceneComponent.prototype.register = function () {
  95885. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  95886. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  95887. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  95888. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  95889. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._draw);
  95890. };
  95891. /**
  95892. * Rebuilds the elements related to this component in case of
  95893. * context lost for instance.
  95894. */
  95895. EffectLayerSceneComponent.prototype.rebuild = function () {
  95896. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  95897. var effectLayer = _a[_i];
  95898. effectLayer._rebuild();
  95899. }
  95900. };
  95901. /**
  95902. * Serializes the component data to the specified json object
  95903. * @param serializationObject The object to serialize to
  95904. */
  95905. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  95906. // Effect layers
  95907. serializationObject.effectLayers = [];
  95908. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  95909. var effectLayer = _a[_i];
  95910. if (effectLayer.serialize) {
  95911. serializationObject.effectLayers.push(effectLayer.serialize());
  95912. }
  95913. }
  95914. };
  95915. /**
  95916. * Adds all the element from the container to the scene
  95917. * @param container the container holding the elements
  95918. */
  95919. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  95920. var _this = this;
  95921. if (!container.effectLayers) {
  95922. return;
  95923. }
  95924. container.effectLayers.forEach(function (o) {
  95925. _this.scene.addEffectLayer(o);
  95926. });
  95927. };
  95928. /**
  95929. * Removes all the elements in the container from the scene
  95930. * @param container contains the elements to remove
  95931. */
  95932. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  95933. var _this = this;
  95934. if (!container.effectLayers) {
  95935. return;
  95936. }
  95937. container.effectLayers.forEach(function (o) {
  95938. _this.scene.removeEffectLayer(o);
  95939. });
  95940. };
  95941. /**
  95942. * Disposes the component and the associated ressources.
  95943. */
  95944. EffectLayerSceneComponent.prototype.dispose = function () {
  95945. while (this._effectLayers.length) {
  95946. this._effectLayers[0].dispose();
  95947. }
  95948. };
  95949. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  95950. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  95951. var layer = _a[_i];
  95952. if (!layer.hasMesh(mesh)) {
  95953. continue;
  95954. }
  95955. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  95956. var subMesh = _c[_b];
  95957. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  95958. return false;
  95959. }
  95960. }
  95961. }
  95962. return true;
  95963. };
  95964. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  95965. this._renderEffects = false;
  95966. this._needStencil = false;
  95967. if (this._effectLayers && this._effectLayers.length > 0) {
  95968. this._previousStencilState = this._engine.getStencilBuffer();
  95969. for (var _i = 0, _a = this._effectLayers; _i < _a.length; _i++) {
  95970. var effectLayer = _a[_i];
  95971. if (effectLayer.shouldRender() &&
  95972. (!effectLayer.camera ||
  95973. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  95974. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  95975. this._renderEffects = true;
  95976. this._needStencil = this._needStencil || effectLayer.needStencil();
  95977. var renderTarget = effectLayer._mainTexture;
  95978. if (renderTarget._shouldRender()) {
  95979. this.scene.incrementRenderId();
  95980. renderTarget.render(false, false);
  95981. }
  95982. }
  95983. }
  95984. this.scene.incrementRenderId();
  95985. }
  95986. };
  95987. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  95988. // Activate effect Layer stencil
  95989. if (this._needStencil) {
  95990. this._engine.setStencilBuffer(true);
  95991. }
  95992. };
  95993. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  95994. // Restore effect Layer stencil
  95995. if (this._needStencil) {
  95996. this._engine.setStencilBuffer(this._previousStencilState);
  95997. }
  95998. };
  95999. EffectLayerSceneComponent.prototype._draw = function (camera) {
  96000. if (this._renderEffects) {
  96001. this._engine.setDepthBuffer(false);
  96002. for (var i = 0; i < this._effectLayers.length; i++) {
  96003. if (this._effectLayers[i].shouldRender()) {
  96004. this._effectLayers[i].render();
  96005. }
  96006. }
  96007. this._engine.setDepthBuffer(true);
  96008. }
  96009. };
  96010. return EffectLayerSceneComponent;
  96011. }());
  96012. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  96013. })(BABYLON || (BABYLON = {}));
  96014. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  96015. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96016. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96017. s = arguments[i];
  96018. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96019. t[p] = s[p];
  96020. }
  96021. return t;
  96022. };
  96023. var BABYLON;
  96024. (function (BABYLON) {
  96025. /**
  96026. * The effect layer Helps adding post process effect blended with the main pass.
  96027. *
  96028. * This can be for instance use to generate glow or higlight effects on the scene.
  96029. *
  96030. * The effect layer class can not be used directly and is intented to inherited from to be
  96031. * customized per effects.
  96032. */
  96033. var EffectLayer = /** @class */ (function () {
  96034. /**
  96035. * Instantiates a new effect Layer and references it in the scene.
  96036. * @param name The name of the layer
  96037. * @param scene The scene to use the layer in
  96038. */
  96039. function EffectLayer(
  96040. /** The Friendly of the effect in the scene */
  96041. name, scene) {
  96042. this._vertexBuffers = {};
  96043. this._maxSize = 0;
  96044. this._mainTextureDesiredSize = { width: 0, height: 0 };
  96045. this._shouldRender = true;
  96046. this._postProcesses = [];
  96047. this._textures = [];
  96048. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  96049. /**
  96050. * The clear color of the texture used to generate the glow map.
  96051. */
  96052. this.neutralColor = new BABYLON.Color4();
  96053. /**
  96054. * Specifies wether the highlight layer is enabled or not.
  96055. */
  96056. this.isEnabled = true;
  96057. /**
  96058. * An event triggered when the effect layer has been disposed.
  96059. */
  96060. this.onDisposeObservable = new BABYLON.Observable();
  96061. /**
  96062. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  96063. */
  96064. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  96065. /**
  96066. * An event triggered when the generated texture is being merged in the scene.
  96067. */
  96068. this.onBeforeComposeObservable = new BABYLON.Observable();
  96069. /**
  96070. * An event triggered when the generated texture has been merged in the scene.
  96071. */
  96072. this.onAfterComposeObservable = new BABYLON.Observable();
  96073. /**
  96074. * An event triggered when the efffect layer changes its size.
  96075. */
  96076. this.onSizeChangedObservable = new BABYLON.Observable();
  96077. this.name = name;
  96078. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  96079. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  96080. if (!component) {
  96081. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  96082. this._scene._addComponent(component);
  96083. }
  96084. this._engine = this._scene.getEngine();
  96085. this._maxSize = this._engine.getCaps().maxTextureSize;
  96086. this._scene.effectLayers.push(this);
  96087. // Generate Buffers
  96088. this._generateIndexBuffer();
  96089. this._genrateVertexBuffer();
  96090. }
  96091. Object.defineProperty(EffectLayer.prototype, "camera", {
  96092. /**
  96093. * Gets the camera attached to the layer.
  96094. */
  96095. get: function () {
  96096. return this._effectLayerOptions.camera;
  96097. },
  96098. enumerable: true,
  96099. configurable: true
  96100. });
  96101. /**
  96102. * Initializes the effect layer with the required options.
  96103. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  96104. */
  96105. EffectLayer.prototype._init = function (options) {
  96106. // Adapt options
  96107. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  96108. this._setMainTextureSize();
  96109. this._createMainTexture();
  96110. this._createTextureAndPostProcesses();
  96111. this._mergeEffect = this._createMergeEffect();
  96112. };
  96113. /**
  96114. * Generates the index buffer of the full screen quad blending to the main canvas.
  96115. */
  96116. EffectLayer.prototype._generateIndexBuffer = function () {
  96117. // Indices
  96118. var indices = [];
  96119. indices.push(0);
  96120. indices.push(1);
  96121. indices.push(2);
  96122. indices.push(0);
  96123. indices.push(2);
  96124. indices.push(3);
  96125. this._indexBuffer = this._engine.createIndexBuffer(indices);
  96126. };
  96127. /**
  96128. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  96129. */
  96130. EffectLayer.prototype._genrateVertexBuffer = function () {
  96131. // VBO
  96132. var vertices = [];
  96133. vertices.push(1, 1);
  96134. vertices.push(-1, 1);
  96135. vertices.push(-1, -1);
  96136. vertices.push(1, -1);
  96137. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  96138. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  96139. };
  96140. /**
  96141. * Sets the main texture desired size which is the closest power of two
  96142. * of the engine canvas size.
  96143. */
  96144. EffectLayer.prototype._setMainTextureSize = function () {
  96145. if (this._effectLayerOptions.mainTextureFixedSize) {
  96146. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  96147. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  96148. }
  96149. else {
  96150. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  96151. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  96152. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  96153. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  96154. }
  96155. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  96156. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  96157. };
  96158. /**
  96159. * Creates the main texture for the effect layer.
  96160. */
  96161. EffectLayer.prototype._createMainTexture = function () {
  96162. var _this = this;
  96163. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  96164. width: this._mainTextureDesiredSize.width,
  96165. height: this._mainTextureDesiredSize.height
  96166. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  96167. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  96168. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96169. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96170. this._mainTexture.anisotropicFilteringLevel = 1;
  96171. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96172. this._mainTexture.renderParticles = false;
  96173. this._mainTexture.renderList = null;
  96174. this._mainTexture.ignoreCameraViewport = true;
  96175. // Custom render function
  96176. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  96177. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  96178. var index;
  96179. var engine = _this._scene.getEngine();
  96180. if (depthOnlySubMeshes.length) {
  96181. engine.setColorWrite(false);
  96182. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  96183. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  96184. }
  96185. engine.setColorWrite(true);
  96186. }
  96187. for (index = 0; index < opaqueSubMeshes.length; index++) {
  96188. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  96189. }
  96190. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  96191. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  96192. }
  96193. for (index = 0; index < transparentSubMeshes.length; index++) {
  96194. _this._renderSubMesh(transparentSubMeshes.data[index]);
  96195. }
  96196. };
  96197. this._mainTexture.onClearObservable.add(function (engine) {
  96198. engine.clear(_this.neutralColor, true, true, true);
  96199. });
  96200. };
  96201. /**
  96202. * Checks for the readiness of the element composing the layer.
  96203. * @param subMesh the mesh to check for
  96204. * @param useInstances specify wether or not to use instances to render the mesh
  96205. * @param emissiveTexture the associated emissive texture used to generate the glow
  96206. * @return true if ready otherwise, false
  96207. */
  96208. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  96209. var material = subMesh.getMaterial();
  96210. if (!material) {
  96211. return false;
  96212. }
  96213. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  96214. return false;
  96215. }
  96216. var defines = [];
  96217. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96218. var mesh = subMesh.getMesh();
  96219. var uv1 = false;
  96220. var uv2 = false;
  96221. // Alpha test
  96222. if (material && material.needAlphaTesting()) {
  96223. var alphaTexture = material.getAlphaTestTexture();
  96224. if (alphaTexture) {
  96225. defines.push("#define ALPHATEST");
  96226. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96227. alphaTexture.coordinatesIndex === 1) {
  96228. defines.push("#define DIFFUSEUV2");
  96229. uv2 = true;
  96230. }
  96231. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96232. defines.push("#define DIFFUSEUV1");
  96233. uv1 = true;
  96234. }
  96235. }
  96236. }
  96237. // Emissive
  96238. if (emissiveTexture) {
  96239. defines.push("#define EMISSIVE");
  96240. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  96241. emissiveTexture.coordinatesIndex === 1) {
  96242. defines.push("#define EMISSIVEUV2");
  96243. uv2 = true;
  96244. }
  96245. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  96246. defines.push("#define EMISSIVEUV1");
  96247. uv1 = true;
  96248. }
  96249. }
  96250. if (uv1) {
  96251. attribs.push(BABYLON.VertexBuffer.UVKind);
  96252. defines.push("#define UV1");
  96253. }
  96254. if (uv2) {
  96255. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96256. defines.push("#define UV2");
  96257. }
  96258. // Bones
  96259. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  96260. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  96261. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  96262. if (mesh.numBoneInfluencers > 4) {
  96263. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  96264. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  96265. }
  96266. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  96267. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  96268. }
  96269. else {
  96270. defines.push("#define NUM_BONE_INFLUENCERS 0");
  96271. }
  96272. // Morph targets
  96273. var manager = mesh.morphTargetManager;
  96274. var morphInfluencers = 0;
  96275. if (manager) {
  96276. if (manager.numInfluencers > 0) {
  96277. defines.push("#define MORPHTARGETS");
  96278. morphInfluencers = manager.numInfluencers;
  96279. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  96280. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  96281. }
  96282. }
  96283. // Instances
  96284. if (useInstances) {
  96285. defines.push("#define INSTANCES");
  96286. attribs.push("world0");
  96287. attribs.push("world1");
  96288. attribs.push("world2");
  96289. attribs.push("world3");
  96290. }
  96291. // Get correct effect
  96292. var join = defines.join("\n");
  96293. if (this._cachedDefines !== join) {
  96294. this._cachedDefines = join;
  96295. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  96296. }
  96297. return this._effectLayerMapGenerationEffect.isReady();
  96298. };
  96299. /**
  96300. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  96301. */
  96302. EffectLayer.prototype.render = function () {
  96303. var currentEffect = this._mergeEffect;
  96304. // Check
  96305. if (!currentEffect.isReady())
  96306. return;
  96307. for (var i = 0; i < this._postProcesses.length; i++) {
  96308. if (!this._postProcesses[i].isReady()) {
  96309. return;
  96310. }
  96311. }
  96312. var engine = this._scene.getEngine();
  96313. this.onBeforeComposeObservable.notifyObservers(this);
  96314. // Render
  96315. engine.enableEffect(currentEffect);
  96316. engine.setState(false);
  96317. // VBOs
  96318. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96319. // Cache
  96320. var previousAlphaMode = engine.getAlphaMode();
  96321. // Go Blend.
  96322. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  96323. // Blends the map on the main canvas.
  96324. this._internalRender(currentEffect);
  96325. // Restore Alpha
  96326. engine.setAlphaMode(previousAlphaMode);
  96327. this.onAfterComposeObservable.notifyObservers(this);
  96328. // Handle size changes.
  96329. var size = this._mainTexture.getSize();
  96330. this._setMainTextureSize();
  96331. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  96332. // Recreate RTT and post processes on size change.
  96333. this.onSizeChangedObservable.notifyObservers(this);
  96334. this._disposeTextureAndPostProcesses();
  96335. this._createMainTexture();
  96336. this._createTextureAndPostProcesses();
  96337. }
  96338. };
  96339. /**
  96340. * Determine if a given mesh will be used in the current effect.
  96341. * @param mesh mesh to test
  96342. * @returns true if the mesh will be used
  96343. */
  96344. EffectLayer.prototype.hasMesh = function (mesh) {
  96345. return true;
  96346. };
  96347. /**
  96348. * Returns true if the layer contains information to display, otherwise false.
  96349. * @returns true if the glow layer should be rendered
  96350. */
  96351. EffectLayer.prototype.shouldRender = function () {
  96352. return this.isEnabled && this._shouldRender;
  96353. };
  96354. /**
  96355. * Returns true if the mesh should render, otherwise false.
  96356. * @param mesh The mesh to render
  96357. * @returns true if it should render otherwise false
  96358. */
  96359. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  96360. return true;
  96361. };
  96362. /**
  96363. * Returns true if the mesh should render, otherwise false.
  96364. * @param mesh The mesh to render
  96365. * @returns true if it should render otherwise false
  96366. */
  96367. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  96368. return true;
  96369. };
  96370. /**
  96371. * Renders the submesh passed in parameter to the generation map.
  96372. */
  96373. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  96374. var _this = this;
  96375. if (!this.shouldRender()) {
  96376. return;
  96377. }
  96378. var material = subMesh.getMaterial();
  96379. var mesh = subMesh.getRenderingMesh();
  96380. var scene = this._scene;
  96381. var engine = scene.getEngine();
  96382. if (!material) {
  96383. return;
  96384. }
  96385. // Do not block in blend mode.
  96386. if (material.needAlphaBlendingForMesh(mesh)) {
  96387. return;
  96388. }
  96389. // Culling
  96390. engine.setState(material.backFaceCulling);
  96391. // Managing instances
  96392. var batch = mesh._getInstancesRenderList(subMesh._id);
  96393. if (batch.mustReturn) {
  96394. return;
  96395. }
  96396. // Early Exit per mesh
  96397. if (!this._shouldRenderMesh(mesh)) {
  96398. return;
  96399. }
  96400. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96401. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  96402. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  96403. engine.enableEffect(this._effectLayerMapGenerationEffect);
  96404. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  96405. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  96406. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  96407. // Alpha test
  96408. if (material && material.needAlphaTesting()) {
  96409. var alphaTexture = material.getAlphaTestTexture();
  96410. if (alphaTexture) {
  96411. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  96412. var textureMatrix = alphaTexture.getTextureMatrix();
  96413. if (textureMatrix) {
  96414. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  96415. }
  96416. }
  96417. }
  96418. // Glow emissive only
  96419. if (this._emissiveTextureAndColor.texture) {
  96420. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  96421. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  96422. }
  96423. // Bones
  96424. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96425. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96426. }
  96427. // Morph targets
  96428. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  96429. // Draw
  96430. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  96431. }
  96432. else {
  96433. // Need to reset refresh rate of the main map
  96434. this._mainTexture.resetRefreshCounter();
  96435. }
  96436. };
  96437. /**
  96438. * Rebuild the required buffers.
  96439. * @hidden Internal use only.
  96440. */
  96441. EffectLayer.prototype._rebuild = function () {
  96442. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96443. if (vb) {
  96444. vb._rebuild();
  96445. }
  96446. this._generateIndexBuffer();
  96447. };
  96448. /**
  96449. * Dispose only the render target textures and post process.
  96450. */
  96451. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  96452. this._mainTexture.dispose();
  96453. for (var i = 0; i < this._postProcesses.length; i++) {
  96454. if (this._postProcesses[i]) {
  96455. this._postProcesses[i].dispose();
  96456. }
  96457. }
  96458. this._postProcesses = [];
  96459. for (var i = 0; i < this._textures.length; i++) {
  96460. if (this._textures[i]) {
  96461. this._textures[i].dispose();
  96462. }
  96463. }
  96464. this._textures = [];
  96465. };
  96466. /**
  96467. * Dispose the highlight layer and free resources.
  96468. */
  96469. EffectLayer.prototype.dispose = function () {
  96470. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96471. if (vertexBuffer) {
  96472. vertexBuffer.dispose();
  96473. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96474. }
  96475. if (this._indexBuffer) {
  96476. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96477. this._indexBuffer = null;
  96478. }
  96479. // Clean textures and post processes
  96480. this._disposeTextureAndPostProcesses();
  96481. // Remove from scene
  96482. var index = this._scene.effectLayers.indexOf(this, 0);
  96483. if (index > -1) {
  96484. this._scene.effectLayers.splice(index, 1);
  96485. }
  96486. // Callback
  96487. this.onDisposeObservable.notifyObservers(this);
  96488. this.onDisposeObservable.clear();
  96489. this.onBeforeRenderMainTextureObservable.clear();
  96490. this.onBeforeComposeObservable.clear();
  96491. this.onAfterComposeObservable.clear();
  96492. this.onSizeChangedObservable.clear();
  96493. };
  96494. /**
  96495. * Gets the class name of the effect layer
  96496. * @returns the string with the class name of the effect layer
  96497. */
  96498. EffectLayer.prototype.getClassName = function () {
  96499. return "EffectLayer";
  96500. };
  96501. /**
  96502. * Creates an effect layer from parsed effect layer data
  96503. * @param parsedEffectLayer defines effect layer data
  96504. * @param scene defines the current scene
  96505. * @param rootUrl defines the root URL containing the effect layer information
  96506. * @returns a parsed effect Layer
  96507. */
  96508. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  96509. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  96510. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  96511. };
  96512. __decorate([
  96513. BABYLON.serialize()
  96514. ], EffectLayer.prototype, "name", void 0);
  96515. __decorate([
  96516. BABYLON.serializeAsColor4()
  96517. ], EffectLayer.prototype, "neutralColor", void 0);
  96518. __decorate([
  96519. BABYLON.serialize()
  96520. ], EffectLayer.prototype, "isEnabled", void 0);
  96521. __decorate([
  96522. BABYLON.serializeAsCameraReference()
  96523. ], EffectLayer.prototype, "camera", null);
  96524. return EffectLayer;
  96525. }());
  96526. BABYLON.EffectLayer = EffectLayer;
  96527. })(BABYLON || (BABYLON = {}));
  96528. //# sourceMappingURL=babylon.effectLayer.js.map
  96529. var BABYLON;
  96530. (function (BABYLON) {
  96531. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  96532. for (var index = 0; index < this.effectLayers.length; index++) {
  96533. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  96534. return this.effectLayers[index];
  96535. }
  96536. }
  96537. return null;
  96538. };
  96539. /**
  96540. * Special Glow Blur post process only blurring the alpha channel
  96541. * It enforces keeping the most luminous color in the color channel.
  96542. */
  96543. var GlowBlurPostProcess = /** @class */ (function (_super) {
  96544. __extends(GlowBlurPostProcess, _super);
  96545. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  96546. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  96547. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  96548. _this.direction = direction;
  96549. _this.kernel = kernel;
  96550. _this.onApplyObservable.add(function (effect) {
  96551. effect.setFloat2("screenSize", _this.width, _this.height);
  96552. effect.setVector2("direction", _this.direction);
  96553. effect.setFloat("blurWidth", _this.kernel);
  96554. });
  96555. return _this;
  96556. }
  96557. return GlowBlurPostProcess;
  96558. }(BABYLON.PostProcess));
  96559. /**
  96560. * The highlight layer Helps adding a glow effect around a mesh.
  96561. *
  96562. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96563. * glowy meshes to your scene.
  96564. *
  96565. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  96566. */
  96567. var HighlightLayer = /** @class */ (function (_super) {
  96568. __extends(HighlightLayer, _super);
  96569. /**
  96570. * Instantiates a new highlight Layer and references it to the scene..
  96571. * @param name The name of the layer
  96572. * @param scene The scene to use the layer in
  96573. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  96574. */
  96575. function HighlightLayer(name, scene, options) {
  96576. var _this = _super.call(this, name, scene) || this;
  96577. _this.name = name;
  96578. /**
  96579. * Specifies whether or not the inner glow is ACTIVE in the layer.
  96580. */
  96581. _this.innerGlow = true;
  96582. /**
  96583. * Specifies whether or not the outer glow is ACTIVE in the layer.
  96584. */
  96585. _this.outerGlow = true;
  96586. /**
  96587. * An event triggered when the highlight layer is being blurred.
  96588. */
  96589. _this.onBeforeBlurObservable = new BABYLON.Observable();
  96590. /**
  96591. * An event triggered when the highlight layer has been blurred.
  96592. */
  96593. _this.onAfterBlurObservable = new BABYLON.Observable();
  96594. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  96595. _this._meshes = {};
  96596. _this._excludedMeshes = {};
  96597. _this.neutralColor = HighlightLayer.NeutralColor;
  96598. // Warn on stencil
  96599. if (!_this._engine.isStencilEnable) {
  96600. 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 }");
  96601. }
  96602. // Adapt options
  96603. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  96604. // Initialize the layer
  96605. _this._init({
  96606. alphaBlendingMode: _this._options.alphaBlendingMode,
  96607. camera: _this._options.camera,
  96608. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96609. mainTextureRatio: _this._options.mainTextureRatio
  96610. });
  96611. // Do not render as long as no meshes have been added
  96612. _this._shouldRender = false;
  96613. return _this;
  96614. }
  96615. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  96616. /**
  96617. * Gets the horizontal size of the blur.
  96618. */
  96619. get: function () {
  96620. return this._horizontalBlurPostprocess.kernel;
  96621. },
  96622. /**
  96623. * Specifies the horizontal size of the blur.
  96624. */
  96625. set: function (value) {
  96626. this._horizontalBlurPostprocess.kernel = value;
  96627. },
  96628. enumerable: true,
  96629. configurable: true
  96630. });
  96631. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  96632. /**
  96633. * Gets the vertical size of the blur.
  96634. */
  96635. get: function () {
  96636. return this._verticalBlurPostprocess.kernel;
  96637. },
  96638. /**
  96639. * Specifies the vertical size of the blur.
  96640. */
  96641. set: function (value) {
  96642. this._verticalBlurPostprocess.kernel = value;
  96643. },
  96644. enumerable: true,
  96645. configurable: true
  96646. });
  96647. /**
  96648. * Get the effect name of the layer.
  96649. * @return The effect name
  96650. */
  96651. HighlightLayer.prototype.getEffectName = function () {
  96652. return HighlightLayer.EffectName;
  96653. };
  96654. /**
  96655. * Create the merge effect. This is the shader use to blit the information back
  96656. * to the main canvas at the end of the scene rendering.
  96657. */
  96658. HighlightLayer.prototype._createMergeEffect = function () {
  96659. // Effect
  96660. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  96661. };
  96662. /**
  96663. * Creates the render target textures and post processes used in the highlight layer.
  96664. */
  96665. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  96666. var _this = this;
  96667. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  96668. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  96669. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96670. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96671. var textureType = 0;
  96672. if (this._engine.getCaps().textureHalfFloatRender) {
  96673. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96674. }
  96675. else {
  96676. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96677. }
  96678. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  96679. width: blurTextureWidth,
  96680. height: blurTextureHeight
  96681. }, this._scene, false, true, textureType);
  96682. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96683. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96684. this._blurTexture.anisotropicFilteringLevel = 16;
  96685. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  96686. this._blurTexture.renderParticles = false;
  96687. this._blurTexture.ignoreCameraViewport = true;
  96688. this._textures = [this._blurTexture];
  96689. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  96690. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96691. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  96692. effect.setTexture("textureSampler", _this._mainTexture);
  96693. });
  96694. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96695. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96696. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96697. });
  96698. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96699. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  96700. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96701. });
  96702. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96703. }
  96704. else {
  96705. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  96706. width: blurTextureWidth,
  96707. height: blurTextureHeight
  96708. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96709. this._horizontalBlurPostprocess.width = blurTextureWidth;
  96710. this._horizontalBlurPostprocess.height = blurTextureHeight;
  96711. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96712. effect.setTexture("textureSampler", _this._mainTexture);
  96713. });
  96714. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  96715. width: blurTextureWidth,
  96716. height: blurTextureHeight
  96717. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96718. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96719. }
  96720. this._mainTexture.onAfterUnbindObservable.add(function () {
  96721. _this.onBeforeBlurObservable.notifyObservers(_this);
  96722. var internalTexture = _this._blurTexture.getInternalTexture();
  96723. if (internalTexture) {
  96724. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  96725. }
  96726. _this.onAfterBlurObservable.notifyObservers(_this);
  96727. });
  96728. // Prevent autoClear.
  96729. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96730. };
  96731. /**
  96732. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96733. */
  96734. HighlightLayer.prototype.needStencil = function () {
  96735. return true;
  96736. };
  96737. /**
  96738. * Checks for the readiness of the element composing the layer.
  96739. * @param subMesh the mesh to check for
  96740. * @param useInstances specify wether or not to use instances to render the mesh
  96741. * @param emissiveTexture the associated emissive texture used to generate the glow
  96742. * @return true if ready otherwise, false
  96743. */
  96744. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  96745. var material = subMesh.getMaterial();
  96746. var mesh = subMesh.getRenderingMesh();
  96747. if (!material || !mesh || !this._meshes) {
  96748. return false;
  96749. }
  96750. var emissiveTexture = null;
  96751. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96752. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96753. emissiveTexture = material.emissiveTexture;
  96754. }
  96755. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96756. };
  96757. /**
  96758. * Implementation specific of rendering the generating effect on the main canvas.
  96759. * @param effect The effect used to render through
  96760. */
  96761. HighlightLayer.prototype._internalRender = function (effect) {
  96762. // Texture
  96763. effect.setTexture("textureSampler", this._blurTexture);
  96764. // Cache
  96765. var engine = this._engine;
  96766. var previousStencilBuffer = engine.getStencilBuffer();
  96767. var previousStencilFunction = engine.getStencilFunction();
  96768. var previousStencilMask = engine.getStencilMask();
  96769. var previousStencilOperationPass = engine.getStencilOperationPass();
  96770. var previousStencilOperationFail = engine.getStencilOperationFail();
  96771. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  96772. var previousStencilReference = engine.getStencilFunctionReference();
  96773. // Stencil operations
  96774. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  96775. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  96776. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  96777. // Draw order
  96778. engine.setStencilMask(0x00);
  96779. engine.setStencilBuffer(true);
  96780. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  96781. // 2 passes inner outer
  96782. if (this.outerGlow) {
  96783. effect.setFloat("offset", 0);
  96784. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  96785. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96786. }
  96787. if (this.innerGlow) {
  96788. effect.setFloat("offset", 1);
  96789. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  96790. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96791. }
  96792. // Restore Cache
  96793. engine.setStencilFunction(previousStencilFunction);
  96794. engine.setStencilMask(previousStencilMask);
  96795. engine.setStencilBuffer(previousStencilBuffer);
  96796. engine.setStencilOperationPass(previousStencilOperationPass);
  96797. engine.setStencilOperationFail(previousStencilOperationFail);
  96798. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  96799. engine.setStencilFunctionReference(previousStencilReference);
  96800. };
  96801. /**
  96802. * Returns true if the layer contains information to display, otherwise false.
  96803. */
  96804. HighlightLayer.prototype.shouldRender = function () {
  96805. if (_super.prototype.shouldRender.call(this)) {
  96806. return this._meshes ? true : false;
  96807. }
  96808. return false;
  96809. };
  96810. /**
  96811. * Returns true if the mesh should render, otherwise false.
  96812. * @param mesh The mesh to render
  96813. * @returns true if it should render otherwise false
  96814. */
  96815. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  96816. // Excluded Mesh
  96817. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  96818. return false;
  96819. }
  96820. ;
  96821. return true;
  96822. };
  96823. /**
  96824. * Sets the required values for both the emissive texture and and the main color.
  96825. */
  96826. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96827. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96828. if (highlightLayerMesh) {
  96829. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  96830. }
  96831. else {
  96832. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96833. }
  96834. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96835. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96836. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  96837. }
  96838. else {
  96839. this._emissiveTextureAndColor.texture = null;
  96840. }
  96841. };
  96842. /**
  96843. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  96844. * @param mesh The mesh to exclude from the highlight layer
  96845. */
  96846. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  96847. if (!this._excludedMeshes) {
  96848. return;
  96849. }
  96850. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96851. if (!meshExcluded) {
  96852. this._excludedMeshes[mesh.uniqueId] = {
  96853. mesh: mesh,
  96854. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  96855. mesh.getEngine().setStencilBuffer(false);
  96856. }),
  96857. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  96858. mesh.getEngine().setStencilBuffer(true);
  96859. }),
  96860. };
  96861. }
  96862. };
  96863. /**
  96864. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  96865. * @param mesh The mesh to highlight
  96866. */
  96867. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  96868. if (!this._excludedMeshes) {
  96869. return;
  96870. }
  96871. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96872. if (meshExcluded) {
  96873. if (meshExcluded.beforeRender) {
  96874. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  96875. }
  96876. if (meshExcluded.afterRender) {
  96877. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  96878. }
  96879. }
  96880. this._excludedMeshes[mesh.uniqueId] = null;
  96881. };
  96882. /**
  96883. * Determine if a given mesh will be highlighted by the current HighlightLayer
  96884. * @param mesh mesh to test
  96885. * @returns true if the mesh will be highlighted by the current HighlightLayer
  96886. */
  96887. HighlightLayer.prototype.hasMesh = function (mesh) {
  96888. if (!this._meshes) {
  96889. return false;
  96890. }
  96891. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  96892. };
  96893. /**
  96894. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  96895. * @param mesh The mesh to highlight
  96896. * @param color The color of the highlight
  96897. * @param glowEmissiveOnly Extract the glow from the emissive texture
  96898. */
  96899. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  96900. var _this = this;
  96901. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  96902. if (!this._meshes) {
  96903. return;
  96904. }
  96905. var meshHighlight = this._meshes[mesh.uniqueId];
  96906. if (meshHighlight) {
  96907. meshHighlight.color = color;
  96908. }
  96909. else {
  96910. this._meshes[mesh.uniqueId] = {
  96911. mesh: mesh,
  96912. color: color,
  96913. // Lambda required for capture due to Observable this context
  96914. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  96915. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  96916. _this._defaultStencilReference(mesh);
  96917. }
  96918. else {
  96919. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  96920. }
  96921. }),
  96922. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  96923. glowEmissiveOnly: glowEmissiveOnly
  96924. };
  96925. mesh.onDisposeObservable.add(function () {
  96926. _this._disposeMesh(mesh);
  96927. });
  96928. }
  96929. this._shouldRender = true;
  96930. };
  96931. /**
  96932. * Remove a mesh from the highlight layer in order to make it stop glowing.
  96933. * @param mesh The mesh to highlight
  96934. */
  96935. HighlightLayer.prototype.removeMesh = function (mesh) {
  96936. if (!this._meshes) {
  96937. return;
  96938. }
  96939. var meshHighlight = this._meshes[mesh.uniqueId];
  96940. if (meshHighlight) {
  96941. if (meshHighlight.observerHighlight) {
  96942. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96943. }
  96944. if (meshHighlight.observerDefault) {
  96945. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96946. }
  96947. delete this._meshes[mesh.uniqueId];
  96948. }
  96949. this._shouldRender = false;
  96950. for (var meshHighlightToCheck in this._meshes) {
  96951. if (this._meshes[meshHighlightToCheck]) {
  96952. this._shouldRender = true;
  96953. break;
  96954. }
  96955. }
  96956. };
  96957. /**
  96958. * Force the stencil to the normal expected value for none glowing parts
  96959. */
  96960. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  96961. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  96962. };
  96963. /**
  96964. * Free any resources and references associated to a mesh.
  96965. * Internal use
  96966. * @param mesh The mesh to free.
  96967. */
  96968. HighlightLayer.prototype._disposeMesh = function (mesh) {
  96969. this.removeMesh(mesh);
  96970. this.removeExcludedMesh(mesh);
  96971. };
  96972. /**
  96973. * Dispose the highlight layer and free resources.
  96974. */
  96975. HighlightLayer.prototype.dispose = function () {
  96976. if (this._meshes) {
  96977. // Clean mesh references
  96978. for (var id in this._meshes) {
  96979. var meshHighlight = this._meshes[id];
  96980. if (meshHighlight && meshHighlight.mesh) {
  96981. if (meshHighlight.observerHighlight) {
  96982. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96983. }
  96984. if (meshHighlight.observerDefault) {
  96985. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96986. }
  96987. }
  96988. }
  96989. this._meshes = null;
  96990. }
  96991. if (this._excludedMeshes) {
  96992. for (var id in this._excludedMeshes) {
  96993. var meshHighlight = this._excludedMeshes[id];
  96994. if (meshHighlight) {
  96995. if (meshHighlight.beforeRender) {
  96996. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  96997. }
  96998. if (meshHighlight.afterRender) {
  96999. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  97000. }
  97001. }
  97002. }
  97003. this._excludedMeshes = null;
  97004. }
  97005. _super.prototype.dispose.call(this);
  97006. };
  97007. /**
  97008. * Gets the class name of the effect layer
  97009. * @returns the string with the class name of the effect layer
  97010. */
  97011. HighlightLayer.prototype.getClassName = function () {
  97012. return "HighlightLayer";
  97013. };
  97014. /**
  97015. * Serializes this Highlight layer
  97016. * @returns a serialized Highlight layer object
  97017. */
  97018. HighlightLayer.prototype.serialize = function () {
  97019. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97020. serializationObject.customType = "BABYLON.HighlightLayer";
  97021. // Highlighted meshes
  97022. serializationObject.meshes = [];
  97023. if (this._meshes) {
  97024. for (var m in this._meshes) {
  97025. var mesh = this._meshes[m];
  97026. if (mesh) {
  97027. serializationObject.meshes.push({
  97028. glowEmissiveOnly: mesh.glowEmissiveOnly,
  97029. color: mesh.color.asArray(),
  97030. meshId: mesh.mesh.id
  97031. });
  97032. }
  97033. }
  97034. }
  97035. // Excluded meshes
  97036. serializationObject.excludedMeshes = [];
  97037. if (this._excludedMeshes) {
  97038. for (var e in this._excludedMeshes) {
  97039. var excludedMesh = this._excludedMeshes[e];
  97040. if (excludedMesh) {
  97041. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  97042. }
  97043. }
  97044. }
  97045. return serializationObject;
  97046. };
  97047. /**
  97048. * Creates a Highlight layer from parsed Highlight layer data
  97049. * @param parsedHightlightLayer defines the Highlight layer data
  97050. * @param scene defines the current scene
  97051. * @param rootUrl defines the root URL containing the Highlight layer information
  97052. * @returns a parsed Highlight layer
  97053. */
  97054. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  97055. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  97056. var index;
  97057. // Excluded meshes
  97058. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  97059. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  97060. if (mesh) {
  97061. hl.addExcludedMesh(mesh);
  97062. }
  97063. }
  97064. // Included meshes
  97065. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  97066. var highlightedMesh = parsedHightlightLayer.meshes[index];
  97067. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  97068. if (mesh) {
  97069. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  97070. }
  97071. }
  97072. return hl;
  97073. };
  97074. /**
  97075. * Effect Name of the highlight layer.
  97076. */
  97077. HighlightLayer.EffectName = "HighlightLayer";
  97078. /**
  97079. * The neutral color used during the preparation of the glow effect.
  97080. * This is black by default as the blend operation is a blend operation.
  97081. */
  97082. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  97083. /**
  97084. * Stencil value used for glowing meshes.
  97085. */
  97086. HighlightLayer.GlowingMeshStencilReference = 0x02;
  97087. /**
  97088. * Stencil value used for the other meshes in the scene.
  97089. */
  97090. HighlightLayer.NormalMeshStencilReference = 0x01;
  97091. __decorate([
  97092. BABYLON.serialize()
  97093. ], HighlightLayer.prototype, "innerGlow", void 0);
  97094. __decorate([
  97095. BABYLON.serialize()
  97096. ], HighlightLayer.prototype, "outerGlow", void 0);
  97097. __decorate([
  97098. BABYLON.serialize()
  97099. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  97100. __decorate([
  97101. BABYLON.serialize()
  97102. ], HighlightLayer.prototype, "blurVerticalSize", null);
  97103. __decorate([
  97104. BABYLON.serialize("options")
  97105. ], HighlightLayer.prototype, "_options", void 0);
  97106. return HighlightLayer;
  97107. }(BABYLON.EffectLayer));
  97108. BABYLON.HighlightLayer = HighlightLayer;
  97109. })(BABYLON || (BABYLON = {}));
  97110. //# sourceMappingURL=babylon.highlightLayer.js.map
  97111. var BABYLON;
  97112. (function (BABYLON) {
  97113. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  97114. for (var index = 0; index < this.effectLayers.length; index++) {
  97115. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  97116. return this.effectLayers[index];
  97117. }
  97118. }
  97119. return null;
  97120. };
  97121. /**
  97122. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  97123. *
  97124. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  97125. * glowy meshes to your scene.
  97126. *
  97127. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  97128. */
  97129. var GlowLayer = /** @class */ (function (_super) {
  97130. __extends(GlowLayer, _super);
  97131. /**
  97132. * Instantiates a new glow Layer and references it to the scene.
  97133. * @param name The name of the layer
  97134. * @param scene The scene to use the layer in
  97135. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  97136. */
  97137. function GlowLayer(name, scene, options) {
  97138. var _this = _super.call(this, name, scene) || this;
  97139. _this._intensity = 1.0;
  97140. _this._includedOnlyMeshes = [];
  97141. _this._excludedMeshes = [];
  97142. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  97143. // Adapt options
  97144. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  97145. // Initialize the layer
  97146. _this._init({
  97147. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  97148. camera: _this._options.camera,
  97149. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  97150. mainTextureRatio: _this._options.mainTextureRatio
  97151. });
  97152. return _this;
  97153. }
  97154. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  97155. /**
  97156. * Gets the kernel size of the blur.
  97157. */
  97158. get: function () {
  97159. return this._horizontalBlurPostprocess1.kernel;
  97160. },
  97161. /**
  97162. * Sets the kernel size of the blur.
  97163. */
  97164. set: function (value) {
  97165. this._horizontalBlurPostprocess1.kernel = value;
  97166. this._verticalBlurPostprocess1.kernel = value;
  97167. this._horizontalBlurPostprocess2.kernel = value;
  97168. this._verticalBlurPostprocess2.kernel = value;
  97169. },
  97170. enumerable: true,
  97171. configurable: true
  97172. });
  97173. Object.defineProperty(GlowLayer.prototype, "intensity", {
  97174. /**
  97175. * Gets the glow intensity.
  97176. */
  97177. get: function () {
  97178. return this._intensity;
  97179. },
  97180. /**
  97181. * Sets the glow intensity.
  97182. */
  97183. set: function (value) {
  97184. this._intensity = value;
  97185. },
  97186. enumerable: true,
  97187. configurable: true
  97188. });
  97189. /**
  97190. * Get the effect name of the layer.
  97191. * @return The effect name
  97192. */
  97193. GlowLayer.prototype.getEffectName = function () {
  97194. return GlowLayer.EffectName;
  97195. };
  97196. /**
  97197. * Create the merge effect. This is the shader use to blit the information back
  97198. * to the main canvas at the end of the scene rendering.
  97199. */
  97200. GlowLayer.prototype._createMergeEffect = function () {
  97201. // Effect
  97202. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  97203. };
  97204. /**
  97205. * Creates the render target textures and post processes used in the glow layer.
  97206. */
  97207. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  97208. var _this = this;
  97209. var blurTextureWidth = this._mainTextureDesiredSize.width;
  97210. var blurTextureHeight = this._mainTextureDesiredSize.height;
  97211. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  97212. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  97213. var textureType = 0;
  97214. if (this._engine.getCaps().textureHalfFloatRender) {
  97215. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97216. }
  97217. else {
  97218. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97219. }
  97220. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  97221. width: blurTextureWidth,
  97222. height: blurTextureHeight
  97223. }, this._scene, false, true, textureType);
  97224. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97225. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97226. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97227. this._blurTexture1.renderParticles = false;
  97228. this._blurTexture1.ignoreCameraViewport = true;
  97229. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  97230. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  97231. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  97232. width: blurTextureWidth2,
  97233. height: blurTextureHeight2
  97234. }, this._scene, false, true, textureType);
  97235. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97236. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97237. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97238. this._blurTexture2.renderParticles = false;
  97239. this._blurTexture2.ignoreCameraViewport = true;
  97240. this._textures = [this._blurTexture1, this._blurTexture2];
  97241. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97242. width: blurTextureWidth,
  97243. height: blurTextureHeight
  97244. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97245. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  97246. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  97247. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  97248. effect.setTexture("textureSampler", _this._mainTexture);
  97249. });
  97250. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97251. width: blurTextureWidth,
  97252. height: blurTextureHeight
  97253. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97254. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  97255. width: blurTextureWidth2,
  97256. height: blurTextureHeight2
  97257. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97258. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  97259. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  97260. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  97261. effect.setTexture("textureSampler", _this._blurTexture1);
  97262. });
  97263. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  97264. width: blurTextureWidth2,
  97265. height: blurTextureHeight2
  97266. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  97267. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97268. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  97269. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  97270. this._mainTexture.samples = this._options.mainTextureSamples;
  97271. this._mainTexture.onAfterUnbindObservable.add(function () {
  97272. var internalTexture = _this._blurTexture1.getInternalTexture();
  97273. if (internalTexture) {
  97274. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  97275. internalTexture = _this._blurTexture2.getInternalTexture();
  97276. if (internalTexture) {
  97277. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  97278. }
  97279. }
  97280. });
  97281. // Prevent autoClear.
  97282. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  97283. };
  97284. /**
  97285. * Checks for the readiness of the element composing the layer.
  97286. * @param subMesh the mesh to check for
  97287. * @param useInstances specify wether or not to use instances to render the mesh
  97288. * @param emissiveTexture the associated emissive texture used to generate the glow
  97289. * @return true if ready otherwise, false
  97290. */
  97291. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  97292. var material = subMesh.getMaterial();
  97293. var mesh = subMesh.getRenderingMesh();
  97294. if (!material || !mesh) {
  97295. return false;
  97296. }
  97297. var emissiveTexture = material.emissiveTexture;
  97298. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  97299. };
  97300. /**
  97301. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  97302. */
  97303. GlowLayer.prototype.needStencil = function () {
  97304. return false;
  97305. };
  97306. /**
  97307. * Implementation specific of rendering the generating effect on the main canvas.
  97308. * @param effect The effect used to render through
  97309. */
  97310. GlowLayer.prototype._internalRender = function (effect) {
  97311. // Texture
  97312. effect.setTexture("textureSampler", this._blurTexture1);
  97313. effect.setTexture("textureSampler2", this._blurTexture2);
  97314. effect.setFloat("offset", this._intensity);
  97315. // Cache
  97316. var engine = this._engine;
  97317. var previousStencilBuffer = engine.getStencilBuffer();
  97318. // Draw order
  97319. engine.setStencilBuffer(false);
  97320. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97321. // Draw order
  97322. engine.setStencilBuffer(previousStencilBuffer);
  97323. };
  97324. /**
  97325. * Sets the required values for both the emissive texture and and the main color.
  97326. */
  97327. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97328. var textureLevel = 1.0;
  97329. if (this.customEmissiveTextureSelector) {
  97330. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  97331. }
  97332. else {
  97333. if (material) {
  97334. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97335. if (this._emissiveTextureAndColor.texture) {
  97336. textureLevel = this._emissiveTextureAndColor.texture.level;
  97337. }
  97338. }
  97339. else {
  97340. this._emissiveTextureAndColor.texture = null;
  97341. }
  97342. }
  97343. if (this.customEmissiveColorSelector) {
  97344. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  97345. }
  97346. else {
  97347. if (material.emissiveColor) {
  97348. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  97349. }
  97350. else {
  97351. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97352. }
  97353. }
  97354. };
  97355. /**
  97356. * Returns true if the mesh should render, otherwise false.
  97357. * @param mesh The mesh to render
  97358. * @returns true if it should render otherwise false
  97359. */
  97360. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  97361. return this.hasMesh(mesh);
  97362. };
  97363. /**
  97364. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  97365. * @param mesh The mesh to exclude from the glow layer
  97366. */
  97367. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  97368. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  97369. this._excludedMeshes.push(mesh.uniqueId);
  97370. }
  97371. };
  97372. /**
  97373. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  97374. * @param mesh The mesh to remove
  97375. */
  97376. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  97377. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  97378. if (index !== -1) {
  97379. this._excludedMeshes.splice(index, 1);
  97380. }
  97381. };
  97382. /**
  97383. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  97384. * @param mesh The mesh to include in the glow layer
  97385. */
  97386. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  97387. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  97388. this._includedOnlyMeshes.push(mesh.uniqueId);
  97389. }
  97390. };
  97391. /**
  97392. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  97393. * @param mesh The mesh to remove
  97394. */
  97395. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  97396. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  97397. if (index !== -1) {
  97398. this._includedOnlyMeshes.splice(index, 1);
  97399. }
  97400. };
  97401. /**
  97402. * Determine if a given mesh will be used in the glow layer
  97403. * @param mesh The mesh to test
  97404. * @returns true if the mesh will be highlighted by the current glow layer
  97405. */
  97406. GlowLayer.prototype.hasMesh = function (mesh) {
  97407. // Included Mesh
  97408. if (this._includedOnlyMeshes.length) {
  97409. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  97410. }
  97411. ;
  97412. // Excluded Mesh
  97413. if (this._excludedMeshes.length) {
  97414. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  97415. }
  97416. ;
  97417. return true;
  97418. };
  97419. /**
  97420. * Free any resources and references associated to a mesh.
  97421. * Internal use
  97422. * @param mesh The mesh to free.
  97423. */
  97424. GlowLayer.prototype._disposeMesh = function (mesh) {
  97425. this.removeIncludedOnlyMesh(mesh);
  97426. this.removeExcludedMesh(mesh);
  97427. };
  97428. /**
  97429. * Gets the class name of the effect layer
  97430. * @returns the string with the class name of the effect layer
  97431. */
  97432. GlowLayer.prototype.getClassName = function () {
  97433. return "GlowLayer";
  97434. };
  97435. /**
  97436. * Serializes this glow layer
  97437. * @returns a serialized glow layer object
  97438. */
  97439. GlowLayer.prototype.serialize = function () {
  97440. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97441. serializationObject.customType = "BABYLON.GlowLayer";
  97442. var index;
  97443. // Included meshes
  97444. serializationObject.includedMeshes = [];
  97445. if (this._includedOnlyMeshes.length) {
  97446. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  97447. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  97448. if (mesh) {
  97449. serializationObject.includedMeshes.push(mesh.id);
  97450. }
  97451. }
  97452. }
  97453. // Excluded meshes
  97454. serializationObject.excludedMeshes = [];
  97455. if (this._excludedMeshes.length) {
  97456. for (index = 0; index < this._excludedMeshes.length; index++) {
  97457. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  97458. if (mesh) {
  97459. serializationObject.excludedMeshes.push(mesh.id);
  97460. }
  97461. }
  97462. }
  97463. return serializationObject;
  97464. };
  97465. /**
  97466. * Creates a Glow Layer from parsed glow layer data
  97467. * @param parsedGlowLayer defines glow layer data
  97468. * @param scene defines the current scene
  97469. * @param rootUrl defines the root URL containing the glow layer information
  97470. * @returns a parsed Glow Layer
  97471. */
  97472. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  97473. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  97474. var index;
  97475. // Excluded meshes
  97476. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  97477. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  97478. if (mesh) {
  97479. gl.addExcludedMesh(mesh);
  97480. }
  97481. }
  97482. // Included meshes
  97483. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  97484. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  97485. if (mesh) {
  97486. gl.addIncludedOnlyMesh(mesh);
  97487. }
  97488. }
  97489. return gl;
  97490. };
  97491. /**
  97492. * Effect Name of the layer.
  97493. */
  97494. GlowLayer.EffectName = "GlowLayer";
  97495. /**
  97496. * The default blur kernel size used for the glow.
  97497. */
  97498. GlowLayer.DefaultBlurKernelSize = 32;
  97499. /**
  97500. * The default texture size ratio used for the glow.
  97501. */
  97502. GlowLayer.DefaultTextureRatio = 0.5;
  97503. __decorate([
  97504. BABYLON.serialize()
  97505. ], GlowLayer.prototype, "blurKernelSize", null);
  97506. __decorate([
  97507. BABYLON.serialize()
  97508. ], GlowLayer.prototype, "intensity", null);
  97509. __decorate([
  97510. BABYLON.serialize("options")
  97511. ], GlowLayer.prototype, "_options", void 0);
  97512. return GlowLayer;
  97513. }(BABYLON.EffectLayer));
  97514. BABYLON.GlowLayer = GlowLayer;
  97515. })(BABYLON || (BABYLON = {}));
  97516. //# sourceMappingURL=babylon.glowLayer.js.map
  97517. var BABYLON;
  97518. (function (BABYLON) {
  97519. /**
  97520. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  97521. */
  97522. var AssetTaskState;
  97523. (function (AssetTaskState) {
  97524. /**
  97525. * Initialization
  97526. */
  97527. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  97528. /**
  97529. * Running
  97530. */
  97531. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  97532. /**
  97533. * Done
  97534. */
  97535. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  97536. /**
  97537. * Error
  97538. */
  97539. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  97540. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  97541. /**
  97542. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  97543. */
  97544. var AbstractAssetTask = /** @class */ (function () {
  97545. /**
  97546. * Creates a new {BABYLON.AssetsManager}
  97547. * @param name defines the name of the task
  97548. */
  97549. function AbstractAssetTask(
  97550. /**
  97551. * Task name
  97552. */ name) {
  97553. this.name = name;
  97554. this._isCompleted = false;
  97555. this._taskState = AssetTaskState.INIT;
  97556. }
  97557. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  97558. /**
  97559. * Get if the task is completed
  97560. */
  97561. get: function () {
  97562. return this._isCompleted;
  97563. },
  97564. enumerable: true,
  97565. configurable: true
  97566. });
  97567. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  97568. /**
  97569. * Gets the current state of the task
  97570. */
  97571. get: function () {
  97572. return this._taskState;
  97573. },
  97574. enumerable: true,
  97575. configurable: true
  97576. });
  97577. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  97578. /**
  97579. * Gets the current error object (if task is in error)
  97580. */
  97581. get: function () {
  97582. return this._errorObject;
  97583. },
  97584. enumerable: true,
  97585. configurable: true
  97586. });
  97587. /**
  97588. * Internal only
  97589. * @hidden
  97590. */
  97591. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  97592. if (this._errorObject) {
  97593. return;
  97594. }
  97595. this._errorObject = {
  97596. message: message,
  97597. exception: exception
  97598. };
  97599. };
  97600. /**
  97601. * Execute the current task
  97602. * @param scene defines the scene where you want your assets to be loaded
  97603. * @param onSuccess is a callback called when the task is successfully executed
  97604. * @param onError is a callback called if an error occurs
  97605. */
  97606. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97607. var _this = this;
  97608. this._taskState = AssetTaskState.RUNNING;
  97609. this.runTask(scene, function () {
  97610. _this.onDoneCallback(onSuccess, onError);
  97611. }, function (msg, exception) {
  97612. _this.onErrorCallback(onError, msg, exception);
  97613. });
  97614. };
  97615. /**
  97616. * Execute the current task
  97617. * @param scene defines the scene where you want your assets to be loaded
  97618. * @param onSuccess is a callback called when the task is successfully executed
  97619. * @param onError is a callback called if an error occurs
  97620. */
  97621. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97622. throw new Error("runTask is not implemented");
  97623. };
  97624. /**
  97625. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  97626. * This can be used with failed tasks that have the reason for failure fixed.
  97627. */
  97628. AbstractAssetTask.prototype.reset = function () {
  97629. this._taskState = AssetTaskState.INIT;
  97630. };
  97631. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  97632. this._taskState = AssetTaskState.ERROR;
  97633. this._errorObject = {
  97634. message: message,
  97635. exception: exception
  97636. };
  97637. if (this.onError) {
  97638. this.onError(this, message, exception);
  97639. }
  97640. onError();
  97641. };
  97642. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  97643. try {
  97644. this._taskState = AssetTaskState.DONE;
  97645. this._isCompleted = true;
  97646. if (this.onSuccess) {
  97647. this.onSuccess(this);
  97648. }
  97649. onSuccess();
  97650. }
  97651. catch (e) {
  97652. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  97653. }
  97654. };
  97655. return AbstractAssetTask;
  97656. }());
  97657. BABYLON.AbstractAssetTask = AbstractAssetTask;
  97658. /**
  97659. * Class used to share progress information about assets loading
  97660. */
  97661. var AssetsProgressEvent = /** @class */ (function () {
  97662. /**
  97663. * Creates a {BABYLON.AssetsProgressEvent}
  97664. * @param remainingCount defines the number of remaining tasks to process
  97665. * @param totalCount defines the total number of tasks
  97666. * @param task defines the task that was just processed
  97667. */
  97668. function AssetsProgressEvent(remainingCount, totalCount, task) {
  97669. this.remainingCount = remainingCount;
  97670. this.totalCount = totalCount;
  97671. this.task = task;
  97672. }
  97673. return AssetsProgressEvent;
  97674. }());
  97675. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  97676. /**
  97677. * Define a task used by {BABYLON.AssetsManager} to load meshes
  97678. */
  97679. var MeshAssetTask = /** @class */ (function (_super) {
  97680. __extends(MeshAssetTask, _super);
  97681. /**
  97682. * Creates a new {BABYLON.MeshAssetTask}
  97683. * @param name defines the name of the task
  97684. * @param meshesNames defines the list of mesh's names you want to load
  97685. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  97686. * @param sceneFilename defines the filename of the scene to load from
  97687. */
  97688. function MeshAssetTask(
  97689. /**
  97690. * Defines the name of the task
  97691. */
  97692. name,
  97693. /**
  97694. * Defines the list of mesh's names you want to load
  97695. */
  97696. meshesNames,
  97697. /**
  97698. * Defines the root url to use as a base to load your meshes and associated resources
  97699. */
  97700. rootUrl,
  97701. /**
  97702. * Defines the filename of the scene to load from
  97703. */
  97704. sceneFilename) {
  97705. var _this = _super.call(this, name) || this;
  97706. _this.name = name;
  97707. _this.meshesNames = meshesNames;
  97708. _this.rootUrl = rootUrl;
  97709. _this.sceneFilename = sceneFilename;
  97710. return _this;
  97711. }
  97712. /**
  97713. * Execute the current task
  97714. * @param scene defines the scene where you want your assets to be loaded
  97715. * @param onSuccess is a callback called when the task is successfully executed
  97716. * @param onError is a callback called if an error occurs
  97717. */
  97718. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97719. var _this = this;
  97720. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  97721. _this.loadedMeshes = meshes;
  97722. _this.loadedParticleSystems = particleSystems;
  97723. _this.loadedSkeletons = skeletons;
  97724. onSuccess();
  97725. }, null, function (scene, message, exception) {
  97726. onError(message, exception);
  97727. });
  97728. };
  97729. return MeshAssetTask;
  97730. }(AbstractAssetTask));
  97731. BABYLON.MeshAssetTask = MeshAssetTask;
  97732. /**
  97733. * Define a task used by {BABYLON.AssetsManager} to load text content
  97734. */
  97735. var TextFileAssetTask = /** @class */ (function (_super) {
  97736. __extends(TextFileAssetTask, _super);
  97737. /**
  97738. * Creates a new TextFileAssetTask object
  97739. * @param name defines the name of the task
  97740. * @param url defines the location of the file to load
  97741. */
  97742. function TextFileAssetTask(
  97743. /**
  97744. * Defines the name of the task
  97745. */
  97746. name,
  97747. /**
  97748. * Defines the location of the file to load
  97749. */
  97750. url) {
  97751. var _this = _super.call(this, name) || this;
  97752. _this.name = name;
  97753. _this.url = url;
  97754. return _this;
  97755. }
  97756. /**
  97757. * Execute the current task
  97758. * @param scene defines the scene where you want your assets to be loaded
  97759. * @param onSuccess is a callback called when the task is successfully executed
  97760. * @param onError is a callback called if an error occurs
  97761. */
  97762. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97763. var _this = this;
  97764. scene._loadFile(this.url, function (data) {
  97765. _this.text = data;
  97766. onSuccess();
  97767. }, undefined, false, false, function (request, exception) {
  97768. if (request) {
  97769. onError(request.status + " " + request.statusText, exception);
  97770. }
  97771. });
  97772. };
  97773. return TextFileAssetTask;
  97774. }(AbstractAssetTask));
  97775. BABYLON.TextFileAssetTask = TextFileAssetTask;
  97776. /**
  97777. * Define a task used by {BABYLON.AssetsManager} to load binary data
  97778. */
  97779. var BinaryFileAssetTask = /** @class */ (function (_super) {
  97780. __extends(BinaryFileAssetTask, _super);
  97781. /**
  97782. * Creates a new BinaryFileAssetTask object
  97783. * @param name defines the name of the new task
  97784. * @param url defines the location of the file to load
  97785. */
  97786. function BinaryFileAssetTask(
  97787. /**
  97788. * Defines the name of the task
  97789. */
  97790. name,
  97791. /**
  97792. * Defines the location of the file to load
  97793. */
  97794. url) {
  97795. var _this = _super.call(this, name) || this;
  97796. _this.name = name;
  97797. _this.url = url;
  97798. return _this;
  97799. }
  97800. /**
  97801. * Execute the current task
  97802. * @param scene defines the scene where you want your assets to be loaded
  97803. * @param onSuccess is a callback called when the task is successfully executed
  97804. * @param onError is a callback called if an error occurs
  97805. */
  97806. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97807. var _this = this;
  97808. scene._loadFile(this.url, function (data) {
  97809. _this.data = data;
  97810. onSuccess();
  97811. }, undefined, true, true, function (request, exception) {
  97812. if (request) {
  97813. onError(request.status + " " + request.statusText, exception);
  97814. }
  97815. });
  97816. };
  97817. return BinaryFileAssetTask;
  97818. }(AbstractAssetTask));
  97819. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  97820. /**
  97821. * Define a task used by {BABYLON.AssetsManager} to load images
  97822. */
  97823. var ImageAssetTask = /** @class */ (function (_super) {
  97824. __extends(ImageAssetTask, _super);
  97825. /**
  97826. * Creates a new ImageAssetTask
  97827. * @param name defines the name of the task
  97828. * @param url defines the location of the image to load
  97829. */
  97830. function ImageAssetTask(
  97831. /**
  97832. * Defines the name of the task
  97833. */
  97834. name,
  97835. /**
  97836. * Defines the location of the image to load
  97837. */
  97838. url) {
  97839. var _this = _super.call(this, name) || this;
  97840. _this.name = name;
  97841. _this.url = url;
  97842. return _this;
  97843. }
  97844. /**
  97845. * Execute the current task
  97846. * @param scene defines the scene where you want your assets to be loaded
  97847. * @param onSuccess is a callback called when the task is successfully executed
  97848. * @param onError is a callback called if an error occurs
  97849. */
  97850. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97851. var _this = this;
  97852. var img = new Image();
  97853. BABYLON.Tools.SetCorsBehavior(this.url, img);
  97854. img.onload = function () {
  97855. _this.image = img;
  97856. onSuccess();
  97857. };
  97858. img.onerror = function (err) {
  97859. onError("Error loading image", err);
  97860. };
  97861. img.src = this.url;
  97862. };
  97863. return ImageAssetTask;
  97864. }(AbstractAssetTask));
  97865. BABYLON.ImageAssetTask = ImageAssetTask;
  97866. /**
  97867. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  97868. */
  97869. var TextureAssetTask = /** @class */ (function (_super) {
  97870. __extends(TextureAssetTask, _super);
  97871. /**
  97872. * Creates a new TextureAssetTask object
  97873. * @param name defines the name of the task
  97874. * @param url defines the location of the file to load
  97875. * @param noMipmap defines if mipmap should not be generated (default is false)
  97876. * @param invertY defines if texture must be inverted on Y axis (default is false)
  97877. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97878. */
  97879. function TextureAssetTask(
  97880. /**
  97881. * Defines the name of the task
  97882. */
  97883. name,
  97884. /**
  97885. * Defines the location of the file to load
  97886. */
  97887. url,
  97888. /**
  97889. * Defines if mipmap should not be generated (default is false)
  97890. */
  97891. noMipmap,
  97892. /**
  97893. * Defines if texture must be inverted on Y axis (default is false)
  97894. */
  97895. invertY,
  97896. /**
  97897. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97898. */
  97899. samplingMode) {
  97900. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97901. var _this = _super.call(this, name) || this;
  97902. _this.name = name;
  97903. _this.url = url;
  97904. _this.noMipmap = noMipmap;
  97905. _this.invertY = invertY;
  97906. _this.samplingMode = samplingMode;
  97907. return _this;
  97908. }
  97909. /**
  97910. * Execute the current task
  97911. * @param scene defines the scene where you want your assets to be loaded
  97912. * @param onSuccess is a callback called when the task is successfully executed
  97913. * @param onError is a callback called if an error occurs
  97914. */
  97915. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97916. var onload = function () {
  97917. onSuccess();
  97918. };
  97919. var onerror = function (message, exception) {
  97920. onError(message, exception);
  97921. };
  97922. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  97923. };
  97924. return TextureAssetTask;
  97925. }(AbstractAssetTask));
  97926. BABYLON.TextureAssetTask = TextureAssetTask;
  97927. /**
  97928. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  97929. */
  97930. var CubeTextureAssetTask = /** @class */ (function (_super) {
  97931. __extends(CubeTextureAssetTask, _super);
  97932. /**
  97933. * Creates a new CubeTextureAssetTask
  97934. * @param name defines the name of the task
  97935. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97936. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97937. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97938. * @param files defines the explicit list of files (undefined by default)
  97939. */
  97940. function CubeTextureAssetTask(
  97941. /**
  97942. * Defines the name of the task
  97943. */
  97944. name,
  97945. /**
  97946. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97947. */
  97948. url,
  97949. /**
  97950. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97951. */
  97952. extensions,
  97953. /**
  97954. * Defines if mipmaps should not be generated (default is false)
  97955. */
  97956. noMipmap,
  97957. /**
  97958. * Defines the explicit list of files (undefined by default)
  97959. */
  97960. files) {
  97961. var _this = _super.call(this, name) || this;
  97962. _this.name = name;
  97963. _this.url = url;
  97964. _this.extensions = extensions;
  97965. _this.noMipmap = noMipmap;
  97966. _this.files = files;
  97967. return _this;
  97968. }
  97969. /**
  97970. * Execute the current task
  97971. * @param scene defines the scene where you want your assets to be loaded
  97972. * @param onSuccess is a callback called when the task is successfully executed
  97973. * @param onError is a callback called if an error occurs
  97974. */
  97975. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97976. var onload = function () {
  97977. onSuccess();
  97978. };
  97979. var onerror = function (message, exception) {
  97980. onError(message, exception);
  97981. };
  97982. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  97983. };
  97984. return CubeTextureAssetTask;
  97985. }(AbstractAssetTask));
  97986. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  97987. /**
  97988. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  97989. */
  97990. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  97991. __extends(HDRCubeTextureAssetTask, _super);
  97992. /**
  97993. * Creates a new HDRCubeTextureAssetTask object
  97994. * @param name defines the name of the task
  97995. * @param url defines the location of the file to load
  97996. * @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.
  97997. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97998. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97999. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  98000. * @param reserved Internal use only
  98001. */
  98002. function HDRCubeTextureAssetTask(
  98003. /**
  98004. * Defines the name of the task
  98005. */
  98006. name,
  98007. /**
  98008. * Defines the location of the file to load
  98009. */
  98010. url,
  98011. /**
  98012. * Defines the desired size (the more it increases the longer the generation will be)
  98013. */
  98014. size,
  98015. /**
  98016. * Defines if mipmaps should not be generated (default is false)
  98017. */
  98018. noMipmap,
  98019. /**
  98020. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  98021. */
  98022. generateHarmonics,
  98023. /**
  98024. * 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)
  98025. */
  98026. gammaSpace,
  98027. /**
  98028. * Internal Use Only
  98029. */
  98030. reserved) {
  98031. if (noMipmap === void 0) { noMipmap = false; }
  98032. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98033. if (gammaSpace === void 0) { gammaSpace = false; }
  98034. if (reserved === void 0) { reserved = false; }
  98035. var _this = _super.call(this, name) || this;
  98036. _this.name = name;
  98037. _this.url = url;
  98038. _this.size = size;
  98039. _this.noMipmap = noMipmap;
  98040. _this.generateHarmonics = generateHarmonics;
  98041. _this.gammaSpace = gammaSpace;
  98042. _this.reserved = reserved;
  98043. return _this;
  98044. }
  98045. /**
  98046. * Execute the current task
  98047. * @param scene defines the scene where you want your assets to be loaded
  98048. * @param onSuccess is a callback called when the task is successfully executed
  98049. * @param onError is a callback called if an error occurs
  98050. */
  98051. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  98052. var onload = function () {
  98053. onSuccess();
  98054. };
  98055. var onerror = function (message, exception) {
  98056. onError(message, exception);
  98057. };
  98058. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  98059. };
  98060. return HDRCubeTextureAssetTask;
  98061. }(AbstractAssetTask));
  98062. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  98063. /**
  98064. * This class can be used to easily import assets into a scene
  98065. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  98066. */
  98067. var AssetsManager = /** @class */ (function () {
  98068. /**
  98069. * Creates a new AssetsManager
  98070. * @param scene defines the scene to work on
  98071. */
  98072. function AssetsManager(scene) {
  98073. this._isLoading = false;
  98074. this._tasks = new Array();
  98075. this._waitingTasksCount = 0;
  98076. this._totalTasksCount = 0;
  98077. /**
  98078. * Observable called when all tasks are processed
  98079. */
  98080. this.onTaskSuccessObservable = new BABYLON.Observable();
  98081. /**
  98082. * Observable called when a task had an error
  98083. */
  98084. this.onTaskErrorObservable = new BABYLON.Observable();
  98085. /**
  98086. * Observable called when a task is successful
  98087. */
  98088. this.onTasksDoneObservable = new BABYLON.Observable();
  98089. /**
  98090. * Observable called when a task is done (whatever the result is)
  98091. */
  98092. this.onProgressObservable = new BABYLON.Observable();
  98093. /**
  98094. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  98095. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  98096. */
  98097. this.useDefaultLoadingScreen = true;
  98098. this._scene = scene;
  98099. }
  98100. /**
  98101. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  98102. * @param taskName defines the name of the new task
  98103. * @param meshesNames defines the name of meshes to load
  98104. * @param rootUrl defines the root url to use to locate files
  98105. * @param sceneFilename defines the filename of the scene file
  98106. * @returns a new {BABYLON.MeshAssetTask} object
  98107. */
  98108. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  98109. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  98110. this._tasks.push(task);
  98111. return task;
  98112. };
  98113. /**
  98114. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  98115. * @param taskName defines the name of the new task
  98116. * @param url defines the url of the file to load
  98117. * @returns a new {BABYLON.TextFileAssetTask} object
  98118. */
  98119. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  98120. var task = new TextFileAssetTask(taskName, url);
  98121. this._tasks.push(task);
  98122. return task;
  98123. };
  98124. /**
  98125. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  98126. * @param taskName defines the name of the new task
  98127. * @param url defines the url of the file to load
  98128. * @returns a new {BABYLON.BinaryFileAssetTask} object
  98129. */
  98130. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  98131. var task = new BinaryFileAssetTask(taskName, url);
  98132. this._tasks.push(task);
  98133. return task;
  98134. };
  98135. /**
  98136. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  98137. * @param taskName defines the name of the new task
  98138. * @param url defines the url of the file to load
  98139. * @returns a new {BABYLON.ImageAssetTask} object
  98140. */
  98141. AssetsManager.prototype.addImageTask = function (taskName, url) {
  98142. var task = new ImageAssetTask(taskName, url);
  98143. this._tasks.push(task);
  98144. return task;
  98145. };
  98146. /**
  98147. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  98148. * @param taskName defines the name of the new task
  98149. * @param url defines the url of the file to load
  98150. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98151. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  98152. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  98153. * @returns a new {BABYLON.TextureAssetTask} object
  98154. */
  98155. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  98156. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98157. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  98158. this._tasks.push(task);
  98159. return task;
  98160. };
  98161. /**
  98162. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  98163. * @param taskName defines the name of the new task
  98164. * @param url defines the url of the file to load
  98165. * @param extensions defines the extension to use to load the cube map (can be null)
  98166. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98167. * @param files defines the list of files to load (can be null)
  98168. * @returns a new {BABYLON.CubeTextureAssetTask} object
  98169. */
  98170. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  98171. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  98172. this._tasks.push(task);
  98173. return task;
  98174. };
  98175. /**
  98176. *
  98177. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  98178. * @param taskName defines the name of the new task
  98179. * @param url defines the url of the file to load
  98180. * @param size defines the size you want for the cubemap (can be null)
  98181. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  98182. * @param generateHarmonics defines if you want to automatically generate (true by default)
  98183. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  98184. * @param reserved Internal use only
  98185. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  98186. */
  98187. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  98188. if (noMipmap === void 0) { noMipmap = false; }
  98189. if (generateHarmonics === void 0) { generateHarmonics = true; }
  98190. if (gammaSpace === void 0) { gammaSpace = false; }
  98191. if (reserved === void 0) { reserved = false; }
  98192. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  98193. this._tasks.push(task);
  98194. return task;
  98195. };
  98196. /**
  98197. * Remove a task from the assets manager.
  98198. * @param task the task to remove
  98199. */
  98200. AssetsManager.prototype.removeTask = function (task) {
  98201. var index = this._tasks.indexOf(task);
  98202. if (index > -1) {
  98203. this._tasks.splice(index, 1);
  98204. }
  98205. };
  98206. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  98207. this._waitingTasksCount--;
  98208. try {
  98209. if (this.onProgress) {
  98210. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  98211. }
  98212. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  98213. }
  98214. catch (e) {
  98215. BABYLON.Tools.Error("Error running progress callbacks.");
  98216. console.log(e);
  98217. }
  98218. if (this._waitingTasksCount === 0) {
  98219. try {
  98220. if (this.onFinish) {
  98221. this.onFinish(this._tasks);
  98222. }
  98223. // Let's remove successfull tasks
  98224. var currentTasks = this._tasks.slice();
  98225. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  98226. var task = currentTasks_1[_i];
  98227. if (task.taskState === AssetTaskState.DONE) {
  98228. var index = this._tasks.indexOf(task);
  98229. if (index > -1) {
  98230. this._tasks.splice(index, 1);
  98231. }
  98232. }
  98233. }
  98234. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98235. }
  98236. catch (e) {
  98237. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  98238. console.log(e);
  98239. }
  98240. this._isLoading = false;
  98241. this._scene.getEngine().hideLoadingUI();
  98242. }
  98243. };
  98244. AssetsManager.prototype._runTask = function (task) {
  98245. var _this = this;
  98246. var done = function () {
  98247. try {
  98248. if (_this.onTaskSuccess) {
  98249. _this.onTaskSuccess(task);
  98250. }
  98251. _this.onTaskSuccessObservable.notifyObservers(task);
  98252. _this._decreaseWaitingTasksCount(task);
  98253. }
  98254. catch (e) {
  98255. error("Error executing task success callbacks", e);
  98256. }
  98257. };
  98258. var error = function (message, exception) {
  98259. task._setErrorObject(message, exception);
  98260. if (_this.onTaskError) {
  98261. _this.onTaskError(task);
  98262. }
  98263. _this.onTaskErrorObservable.notifyObservers(task);
  98264. _this._decreaseWaitingTasksCount(task);
  98265. };
  98266. task.run(this._scene, done, error);
  98267. };
  98268. /**
  98269. * Reset the {BABYLON.AssetsManager} and remove all tasks
  98270. * @return the current instance of the {BABYLON.AssetsManager}
  98271. */
  98272. AssetsManager.prototype.reset = function () {
  98273. this._isLoading = false;
  98274. this._tasks = new Array();
  98275. return this;
  98276. };
  98277. /**
  98278. * Start the loading process
  98279. * @return the current instance of the {BABYLON.AssetsManager}
  98280. */
  98281. AssetsManager.prototype.load = function () {
  98282. if (this._isLoading) {
  98283. return this;
  98284. }
  98285. this._isLoading = true;
  98286. this._waitingTasksCount = this._tasks.length;
  98287. this._totalTasksCount = this._tasks.length;
  98288. if (this._waitingTasksCount === 0) {
  98289. this._isLoading = false;
  98290. if (this.onFinish) {
  98291. this.onFinish(this._tasks);
  98292. }
  98293. this.onTasksDoneObservable.notifyObservers(this._tasks);
  98294. return this;
  98295. }
  98296. if (this.useDefaultLoadingScreen) {
  98297. this._scene.getEngine().displayLoadingUI();
  98298. }
  98299. for (var index = 0; index < this._tasks.length; index++) {
  98300. var task = this._tasks[index];
  98301. if (task.taskState === AssetTaskState.INIT) {
  98302. this._runTask(task);
  98303. }
  98304. }
  98305. return this;
  98306. };
  98307. return AssetsManager;
  98308. }());
  98309. BABYLON.AssetsManager = AssetsManager;
  98310. })(BABYLON || (BABYLON = {}));
  98311. //# sourceMappingURL=babylon.assetsManager.js.map
  98312. var BABYLON;
  98313. (function (BABYLON) {
  98314. var serializedGeometries = [];
  98315. var serializeGeometry = function (geometry, serializationGeometries) {
  98316. if (serializedGeometries[geometry.id]) {
  98317. return;
  98318. }
  98319. if (geometry.doNotSerialize) {
  98320. return;
  98321. }
  98322. if (geometry instanceof BABYLON.BoxGeometry) {
  98323. serializationGeometries.boxes.push(geometry.serialize());
  98324. }
  98325. else if (geometry instanceof BABYLON.SphereGeometry) {
  98326. serializationGeometries.spheres.push(geometry.serialize());
  98327. }
  98328. else if (geometry instanceof BABYLON.CylinderGeometry) {
  98329. serializationGeometries.cylinders.push(geometry.serialize());
  98330. }
  98331. else if (geometry instanceof BABYLON.TorusGeometry) {
  98332. serializationGeometries.toruses.push(geometry.serialize());
  98333. }
  98334. else if (geometry instanceof BABYLON.GroundGeometry) {
  98335. serializationGeometries.grounds.push(geometry.serialize());
  98336. }
  98337. else if (geometry instanceof BABYLON.Plane) {
  98338. serializationGeometries.planes.push(geometry.serialize());
  98339. }
  98340. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  98341. serializationGeometries.torusKnots.push(geometry.serialize());
  98342. }
  98343. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  98344. throw new Error("Unknown primitive type");
  98345. }
  98346. else {
  98347. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  98348. }
  98349. serializedGeometries[geometry.id] = true;
  98350. };
  98351. var serializeMesh = function (mesh, serializationScene) {
  98352. var serializationObject = {};
  98353. // Geometry
  98354. var geometry = mesh._geometry;
  98355. if (geometry) {
  98356. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  98357. // 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
  98358. serializeGeometry(geometry, serializationScene.geometries);
  98359. }
  98360. }
  98361. // Custom
  98362. if (mesh.serialize) {
  98363. mesh.serialize(serializationObject);
  98364. }
  98365. return serializationObject;
  98366. };
  98367. var finalizeSingleMesh = function (mesh, serializationObject) {
  98368. //only works if the mesh is already loaded
  98369. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98370. //serialize material
  98371. if (mesh.material) {
  98372. if (mesh.material instanceof BABYLON.MultiMaterial) {
  98373. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  98374. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98375. serializationObject.multiMaterials.push(mesh.material.serialize());
  98376. }
  98377. }
  98378. else {
  98379. serializationObject.materials = serializationObject.materials || [];
  98380. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98381. serializationObject.materials.push(mesh.material.serialize());
  98382. }
  98383. }
  98384. }
  98385. //serialize geometry
  98386. var geometry = mesh._geometry;
  98387. if (geometry) {
  98388. if (!serializationObject.geometries) {
  98389. serializationObject.geometries = {};
  98390. serializationObject.geometries.boxes = [];
  98391. serializationObject.geometries.spheres = [];
  98392. serializationObject.geometries.cylinders = [];
  98393. serializationObject.geometries.toruses = [];
  98394. serializationObject.geometries.grounds = [];
  98395. serializationObject.geometries.planes = [];
  98396. serializationObject.geometries.torusKnots = [];
  98397. serializationObject.geometries.vertexData = [];
  98398. }
  98399. serializeGeometry(geometry, serializationObject.geometries);
  98400. }
  98401. // Skeletons
  98402. if (mesh.skeleton) {
  98403. serializationObject.skeletons = serializationObject.skeletons || [];
  98404. serializationObject.skeletons.push(mesh.skeleton.serialize());
  98405. }
  98406. //serialize the actual mesh
  98407. serializationObject.meshes = serializationObject.meshes || [];
  98408. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98409. }
  98410. };
  98411. var SceneSerializer = /** @class */ (function () {
  98412. function SceneSerializer() {
  98413. }
  98414. SceneSerializer.ClearCache = function () {
  98415. serializedGeometries = [];
  98416. };
  98417. SceneSerializer.Serialize = function (scene) {
  98418. var serializationObject = {};
  98419. SceneSerializer.ClearCache();
  98420. // Scene
  98421. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  98422. serializationObject.autoClear = scene.autoClear;
  98423. serializationObject.clearColor = scene.clearColor.asArray();
  98424. serializationObject.ambientColor = scene.ambientColor.asArray();
  98425. serializationObject.gravity = scene.gravity.asArray();
  98426. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  98427. serializationObject.workerCollisions = scene.workerCollisions;
  98428. // Fog
  98429. if (scene.fogMode && scene.fogMode !== 0) {
  98430. serializationObject.fogMode = scene.fogMode;
  98431. serializationObject.fogColor = scene.fogColor.asArray();
  98432. serializationObject.fogStart = scene.fogStart;
  98433. serializationObject.fogEnd = scene.fogEnd;
  98434. serializationObject.fogDensity = scene.fogDensity;
  98435. }
  98436. //Physics
  98437. if (scene.isPhysicsEnabled()) {
  98438. var physicEngine = scene.getPhysicsEngine();
  98439. if (physicEngine) {
  98440. serializationObject.physicsEnabled = true;
  98441. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  98442. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  98443. }
  98444. }
  98445. // Metadata
  98446. if (scene.metadata) {
  98447. serializationObject.metadata = scene.metadata;
  98448. }
  98449. // Morph targets
  98450. serializationObject.morphTargetManagers = [];
  98451. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  98452. var abstractMesh = _a[_i];
  98453. var manager = abstractMesh.morphTargetManager;
  98454. if (manager) {
  98455. serializationObject.morphTargetManagers.push(manager.serialize());
  98456. }
  98457. }
  98458. // Lights
  98459. serializationObject.lights = [];
  98460. var index;
  98461. var light;
  98462. for (index = 0; index < scene.lights.length; index++) {
  98463. light = scene.lights[index];
  98464. if (!light.doNotSerialize) {
  98465. serializationObject.lights.push(light.serialize());
  98466. }
  98467. }
  98468. // Cameras
  98469. serializationObject.cameras = [];
  98470. for (index = 0; index < scene.cameras.length; index++) {
  98471. var camera = scene.cameras[index];
  98472. if (!camera.doNotSerialize) {
  98473. serializationObject.cameras.push(camera.serialize());
  98474. }
  98475. }
  98476. if (scene.activeCamera) {
  98477. serializationObject.activeCameraID = scene.activeCamera.id;
  98478. }
  98479. // Animations
  98480. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  98481. // Materials
  98482. serializationObject.materials = [];
  98483. serializationObject.multiMaterials = [];
  98484. var material;
  98485. for (index = 0; index < scene.materials.length; index++) {
  98486. material = scene.materials[index];
  98487. if (!material.doNotSerialize) {
  98488. serializationObject.materials.push(material.serialize());
  98489. }
  98490. }
  98491. // MultiMaterials
  98492. serializationObject.multiMaterials = [];
  98493. for (index = 0; index < scene.multiMaterials.length; index++) {
  98494. var multiMaterial = scene.multiMaterials[index];
  98495. serializationObject.multiMaterials.push(multiMaterial.serialize());
  98496. }
  98497. // Environment texture
  98498. if (scene.environmentTexture) {
  98499. serializationObject.environmentTexture = scene.environmentTexture.name;
  98500. }
  98501. // Skeletons
  98502. serializationObject.skeletons = [];
  98503. for (index = 0; index < scene.skeletons.length; index++) {
  98504. var skeleton = scene.skeletons[index];
  98505. if (!skeleton.doNotSerialize) {
  98506. serializationObject.skeletons.push(skeleton.serialize());
  98507. }
  98508. }
  98509. // Transform nodes
  98510. serializationObject.transformNodes = [];
  98511. for (index = 0; index < scene.transformNodes.length; index++) {
  98512. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  98513. }
  98514. // Geometries
  98515. serializationObject.geometries = {};
  98516. serializationObject.geometries.boxes = [];
  98517. serializationObject.geometries.spheres = [];
  98518. serializationObject.geometries.cylinders = [];
  98519. serializationObject.geometries.toruses = [];
  98520. serializationObject.geometries.grounds = [];
  98521. serializationObject.geometries.planes = [];
  98522. serializationObject.geometries.torusKnots = [];
  98523. serializationObject.geometries.vertexData = [];
  98524. serializedGeometries = [];
  98525. var geometries = scene.getGeometries();
  98526. for (index = 0; index < geometries.length; index++) {
  98527. var geometry = geometries[index];
  98528. if (geometry.isReady()) {
  98529. serializeGeometry(geometry, serializationObject.geometries);
  98530. }
  98531. }
  98532. // Meshes
  98533. serializationObject.meshes = [];
  98534. for (index = 0; index < scene.meshes.length; index++) {
  98535. var abstractMesh = scene.meshes[index];
  98536. if (abstractMesh instanceof BABYLON.Mesh) {
  98537. var mesh = abstractMesh;
  98538. if (!mesh.doNotSerialize) {
  98539. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98540. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98541. }
  98542. }
  98543. }
  98544. }
  98545. // Particles Systems
  98546. serializationObject.particleSystems = [];
  98547. for (index = 0; index < scene.particleSystems.length; index++) {
  98548. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  98549. }
  98550. // Shadows
  98551. serializationObject.shadowGenerators = [];
  98552. for (index = 0; index < scene.lights.length; index++) {
  98553. light = scene.lights[index];
  98554. var shadowGenerator = light.getShadowGenerator();
  98555. if (shadowGenerator) {
  98556. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  98557. }
  98558. }
  98559. // Action Manager
  98560. if (scene.actionManager) {
  98561. serializationObject.actions = scene.actionManager.serialize("scene");
  98562. }
  98563. // Audio
  98564. serializationObject.sounds = [];
  98565. for (index = 0; index < scene.soundTracks.length; index++) {
  98566. var soundtrack = scene.soundTracks[index];
  98567. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  98568. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  98569. }
  98570. }
  98571. // Components
  98572. for (var _b = 0, _c = scene._components; _b < _c.length; _b++) {
  98573. var component = _c[_b];
  98574. component.serialize(serializationObject);
  98575. }
  98576. return serializationObject;
  98577. };
  98578. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  98579. if (withParents === void 0) { withParents = false; }
  98580. if (withChildren === void 0) { withChildren = false; }
  98581. var serializationObject = {};
  98582. SceneSerializer.ClearCache();
  98583. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  98584. if (withParents || withChildren) {
  98585. //deliberate for loop! not for each, appended should be processed as well.
  98586. for (var i = 0; i < toSerialize.length; ++i) {
  98587. if (withChildren) {
  98588. toSerialize[i].getDescendants().forEach(function (node) {
  98589. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  98590. toSerialize.push(node);
  98591. }
  98592. });
  98593. }
  98594. //make sure the array doesn't contain the object already
  98595. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  98596. toSerialize.push(toSerialize[i].parent);
  98597. }
  98598. }
  98599. }
  98600. toSerialize.forEach(function (mesh) {
  98601. finalizeSingleMesh(mesh, serializationObject);
  98602. });
  98603. return serializationObject;
  98604. };
  98605. return SceneSerializer;
  98606. }());
  98607. BABYLON.SceneSerializer = SceneSerializer;
  98608. })(BABYLON || (BABYLON = {}));
  98609. //# sourceMappingURL=babylon.sceneSerializer.js.map
  98610. var BABYLON;
  98611. (function (BABYLON) {
  98612. var ReflectionProbe = /** @class */ (function () {
  98613. function ReflectionProbe(name, size, scene, generateMipMaps) {
  98614. if (generateMipMaps === void 0) { generateMipMaps = true; }
  98615. var _this = this;
  98616. this.name = name;
  98617. this._viewMatrix = BABYLON.Matrix.Identity();
  98618. this._target = BABYLON.Vector3.Zero();
  98619. this._add = BABYLON.Vector3.Zero();
  98620. this._invertYAxis = false;
  98621. this.position = BABYLON.Vector3.Zero();
  98622. this._scene = scene;
  98623. this._scene.reflectionProbes.push(this);
  98624. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  98625. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  98626. switch (faceIndex) {
  98627. case 0:
  98628. _this._add.copyFromFloats(1, 0, 0);
  98629. break;
  98630. case 1:
  98631. _this._add.copyFromFloats(-1, 0, 0);
  98632. break;
  98633. case 2:
  98634. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  98635. break;
  98636. case 3:
  98637. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  98638. break;
  98639. case 4:
  98640. _this._add.copyFromFloats(0, 0, 1);
  98641. break;
  98642. case 5:
  98643. _this._add.copyFromFloats(0, 0, -1);
  98644. break;
  98645. }
  98646. if (_this._attachedMesh) {
  98647. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  98648. }
  98649. _this.position.addToRef(_this._add, _this._target);
  98650. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  98651. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  98652. scene._forcedViewPosition = _this.position;
  98653. });
  98654. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  98655. scene._forcedViewPosition = null;
  98656. scene.updateTransformMatrix(true);
  98657. });
  98658. if (scene.activeCamera) {
  98659. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  98660. }
  98661. }
  98662. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  98663. get: function () {
  98664. return this._renderTargetTexture.samples;
  98665. },
  98666. set: function (value) {
  98667. this._renderTargetTexture.samples = value;
  98668. },
  98669. enumerable: true,
  98670. configurable: true
  98671. });
  98672. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  98673. get: function () {
  98674. return this._renderTargetTexture.refreshRate;
  98675. },
  98676. set: function (value) {
  98677. this._renderTargetTexture.refreshRate = value;
  98678. },
  98679. enumerable: true,
  98680. configurable: true
  98681. });
  98682. ReflectionProbe.prototype.getScene = function () {
  98683. return this._scene;
  98684. };
  98685. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  98686. get: function () {
  98687. return this._renderTargetTexture;
  98688. },
  98689. enumerable: true,
  98690. configurable: true
  98691. });
  98692. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  98693. get: function () {
  98694. return this._renderTargetTexture.renderList;
  98695. },
  98696. enumerable: true,
  98697. configurable: true
  98698. });
  98699. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  98700. this._attachedMesh = mesh;
  98701. };
  98702. /**
  98703. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  98704. *
  98705. * @param renderingGroupId The rendering group id corresponding to its index
  98706. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  98707. */
  98708. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  98709. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  98710. };
  98711. ReflectionProbe.prototype.dispose = function () {
  98712. var index = this._scene.reflectionProbes.indexOf(this);
  98713. if (index !== -1) {
  98714. // Remove from the scene if found
  98715. this._scene.reflectionProbes.splice(index, 1);
  98716. }
  98717. if (this._renderTargetTexture) {
  98718. this._renderTargetTexture.dispose();
  98719. this._renderTargetTexture = null;
  98720. }
  98721. };
  98722. return ReflectionProbe;
  98723. }());
  98724. BABYLON.ReflectionProbe = ReflectionProbe;
  98725. })(BABYLON || (BABYLON = {}));
  98726. //# sourceMappingURL=babylon.reflectionProbe.js.map
  98727. var BABYLON;
  98728. (function (BABYLON) {
  98729. /**
  98730. * Defines the layer scene component responsible to manage any layers
  98731. * in a given scene.
  98732. */
  98733. var LayerSceneComponent = /** @class */ (function () {
  98734. /**
  98735. * Creates a new instance of the component for the given scene
  98736. * @param scene Defines the scene to register the component in
  98737. */
  98738. function LayerSceneComponent(scene) {
  98739. /**
  98740. * The component name helpfull to identify the component in the list of scene components.
  98741. */
  98742. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  98743. this.scene = scene;
  98744. this._engine = scene.getEngine();
  98745. this._layers = scene.layers = new Array();
  98746. }
  98747. /**
  98748. * Registers the component in a given scene
  98749. */
  98750. LayerSceneComponent.prototype.register = function () {
  98751. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  98752. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  98753. };
  98754. /**
  98755. * Rebuilds the elements related to this component in case of
  98756. * context lost for instance.
  98757. */
  98758. LayerSceneComponent.prototype.rebuild = function () {
  98759. for (var _i = 0, _a = this._layers; _i < _a.length; _i++) {
  98760. var layer = _a[_i];
  98761. layer._rebuild();
  98762. }
  98763. };
  98764. /**
  98765. * Serializes the component data to the specified json object
  98766. * @param serializationObject The object to serialize to
  98767. */
  98768. LayerSceneComponent.prototype.serialize = function (serializationObject) {
  98769. // TODO. Implement layer serialization
  98770. // serializationObject.layers = [];
  98771. // for (let layer of this._layers) {
  98772. // if (layer.serialize) {
  98773. // serializationObject.layers.push(layer.serialize());
  98774. // }
  98775. // }
  98776. };
  98777. /**
  98778. * Adds all the element from the container to the scene
  98779. * @param container the container holding the elements
  98780. */
  98781. LayerSceneComponent.prototype.addFromContainer = function (container) {
  98782. if (!container.layers) {
  98783. return;
  98784. }
  98785. // container.layers.forEach((o) => {
  98786. // this.scene.addLayer(o);
  98787. // });
  98788. };
  98789. /**
  98790. * Removes all the elements in the container from the scene
  98791. * @param container contains the elements to remove
  98792. */
  98793. LayerSceneComponent.prototype.removeFromContainer = function (container) {
  98794. if (!container.layers) {
  98795. return;
  98796. }
  98797. // container.layers.forEach((o) => {
  98798. // this.scene.removeLayer(o);
  98799. // });
  98800. };
  98801. /**
  98802. * Disposes the component and the associated ressources.
  98803. */
  98804. LayerSceneComponent.prototype.dispose = function () {
  98805. while (this._layers.length) {
  98806. this._layers[0].dispose();
  98807. }
  98808. };
  98809. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  98810. if (this._layers.length) {
  98811. this._engine.setDepthBuffer(false);
  98812. var cameraLayerMask = camera.layerMask;
  98813. for (var _i = 0, _a = this._layers; _i < _a.length; _i++) {
  98814. var layer = _a[_i];
  98815. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  98816. layer.render();
  98817. }
  98818. }
  98819. this._engine.setDepthBuffer(true);
  98820. }
  98821. };
  98822. LayerSceneComponent.prototype._drawBackground = function (camera) {
  98823. this._draw(camera, true);
  98824. };
  98825. LayerSceneComponent.prototype._drawForeground = function (camera) {
  98826. this._draw(camera, false);
  98827. };
  98828. return LayerSceneComponent;
  98829. }());
  98830. BABYLON.LayerSceneComponent = LayerSceneComponent;
  98831. })(BABYLON || (BABYLON = {}));
  98832. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  98833. var BABYLON;
  98834. (function (BABYLON) {
  98835. var Layer = /** @class */ (function () {
  98836. function Layer(name, imgUrl, scene, isBackground, color) {
  98837. this.name = name;
  98838. this.scale = new BABYLON.Vector2(1, 1);
  98839. this.offset = new BABYLON.Vector2(0, 0);
  98840. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  98841. this.layerMask = 0x0FFFFFFF;
  98842. this._vertexBuffers = {};
  98843. // Events
  98844. /**
  98845. * An event triggered when the layer is disposed.
  98846. */
  98847. this.onDisposeObservable = new BABYLON.Observable();
  98848. /**
  98849. * An event triggered before rendering the scene
  98850. */
  98851. this.onBeforeRenderObservable = new BABYLON.Observable();
  98852. /**
  98853. * An event triggered after rendering the scene
  98854. */
  98855. this.onAfterRenderObservable = new BABYLON.Observable();
  98856. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  98857. this.isBackground = isBackground === undefined ? true : isBackground;
  98858. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  98859. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  98860. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  98861. if (!layerComponent) {
  98862. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  98863. this._scene._addComponent(layerComponent);
  98864. }
  98865. this._scene.layers.push(this);
  98866. var engine = this._scene.getEngine();
  98867. // VBO
  98868. var vertices = [];
  98869. vertices.push(1, 1);
  98870. vertices.push(-1, 1);
  98871. vertices.push(-1, -1);
  98872. vertices.push(1, -1);
  98873. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  98874. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  98875. this._createIndexBuffer();
  98876. // Effects
  98877. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  98878. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  98879. }
  98880. Object.defineProperty(Layer.prototype, "onDispose", {
  98881. set: function (callback) {
  98882. if (this._onDisposeObserver) {
  98883. this.onDisposeObservable.remove(this._onDisposeObserver);
  98884. }
  98885. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  98886. },
  98887. enumerable: true,
  98888. configurable: true
  98889. });
  98890. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  98891. set: function (callback) {
  98892. if (this._onBeforeRenderObserver) {
  98893. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  98894. }
  98895. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  98896. },
  98897. enumerable: true,
  98898. configurable: true
  98899. });
  98900. Object.defineProperty(Layer.prototype, "onAfterRender", {
  98901. set: function (callback) {
  98902. if (this._onAfterRenderObserver) {
  98903. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98904. }
  98905. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  98906. },
  98907. enumerable: true,
  98908. configurable: true
  98909. });
  98910. Layer.prototype._createIndexBuffer = function () {
  98911. var engine = this._scene.getEngine();
  98912. // Indices
  98913. var indices = [];
  98914. indices.push(0);
  98915. indices.push(1);
  98916. indices.push(2);
  98917. indices.push(0);
  98918. indices.push(2);
  98919. indices.push(3);
  98920. this._indexBuffer = engine.createIndexBuffer(indices);
  98921. };
  98922. Layer.prototype._rebuild = function () {
  98923. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98924. if (vb) {
  98925. vb._rebuild();
  98926. }
  98927. this._createIndexBuffer();
  98928. };
  98929. Layer.prototype.render = function () {
  98930. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  98931. // Check
  98932. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  98933. return;
  98934. var engine = this._scene.getEngine();
  98935. this.onBeforeRenderObservable.notifyObservers(this);
  98936. // Render
  98937. engine.enableEffect(currentEffect);
  98938. engine.setState(false);
  98939. // Texture
  98940. currentEffect.setTexture("textureSampler", this.texture);
  98941. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  98942. // Color
  98943. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  98944. // Scale / offset
  98945. currentEffect.setVector2("offset", this.offset);
  98946. currentEffect.setVector2("scale", this.scale);
  98947. // VBOs
  98948. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  98949. // Draw order
  98950. if (!this.alphaTest) {
  98951. engine.setAlphaMode(this.alphaBlendingMode);
  98952. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98953. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  98954. }
  98955. else {
  98956. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98957. }
  98958. this.onAfterRenderObservable.notifyObservers(this);
  98959. };
  98960. Layer.prototype.dispose = function () {
  98961. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98962. if (vertexBuffer) {
  98963. vertexBuffer.dispose();
  98964. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  98965. }
  98966. if (this._indexBuffer) {
  98967. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  98968. this._indexBuffer = null;
  98969. }
  98970. if (this.texture) {
  98971. this.texture.dispose();
  98972. this.texture = null;
  98973. }
  98974. // Remove from scene
  98975. var index = this._scene.layers.indexOf(this);
  98976. this._scene.layers.splice(index, 1);
  98977. // Callback
  98978. this.onDisposeObservable.notifyObservers(this);
  98979. this.onDisposeObservable.clear();
  98980. this.onAfterRenderObservable.clear();
  98981. this.onBeforeRenderObservable.clear();
  98982. };
  98983. return Layer;
  98984. }());
  98985. BABYLON.Layer = Layer;
  98986. })(BABYLON || (BABYLON = {}));
  98987. //# sourceMappingURL=babylon.layer.js.map
  98988. var BABYLON;
  98989. (function (BABYLON) {
  98990. var TextureTools = /** @class */ (function () {
  98991. function TextureTools() {
  98992. }
  98993. /**
  98994. * Uses the GPU to create a copy texture rescaled at a given size
  98995. * @param texture Texture to copy from
  98996. * @param width Desired width
  98997. * @param height Desired height
  98998. * @return Generated texture
  98999. */
  99000. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  99001. if (useBilinearMode === void 0) { useBilinearMode = true; }
  99002. var scene = texture.getScene();
  99003. var engine = scene.getEngine();
  99004. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  99005. rtt.wrapU = texture.wrapU;
  99006. rtt.wrapV = texture.wrapV;
  99007. rtt.uOffset = texture.uOffset;
  99008. rtt.vOffset = texture.vOffset;
  99009. rtt.uScale = texture.uScale;
  99010. rtt.vScale = texture.vScale;
  99011. rtt.uAng = texture.uAng;
  99012. rtt.vAng = texture.vAng;
  99013. rtt.wAng = texture.wAng;
  99014. rtt.coordinatesIndex = texture.coordinatesIndex;
  99015. rtt.level = texture.level;
  99016. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  99017. rtt._texture.isReady = false;
  99018. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99019. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99020. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  99021. passPostProcess.getEffect().executeWhenCompiled(function () {
  99022. passPostProcess.onApply = function (effect) {
  99023. effect.setTexture("textureSampler", texture);
  99024. };
  99025. var internalTexture = rtt.getInternalTexture();
  99026. if (internalTexture) {
  99027. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  99028. engine.unBindFramebuffer(internalTexture);
  99029. rtt.disposeFramebufferObjects();
  99030. passPostProcess.dispose();
  99031. internalTexture.isReady = true;
  99032. }
  99033. });
  99034. return rtt;
  99035. };
  99036. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  99037. if (!scene._environmentBRDFTexture) {
  99038. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  99039. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99040. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  99041. scene._environmentBRDFTexture = texture;
  99042. }
  99043. return scene._environmentBRDFTexture;
  99044. };
  99045. 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=";
  99046. return TextureTools;
  99047. }());
  99048. BABYLON.TextureTools = TextureTools;
  99049. })(BABYLON || (BABYLON = {}));
  99050. //# sourceMappingURL=babylon.textureTools.js.map
  99051. var BABYLON;
  99052. (function (BABYLON) {
  99053. var FramingBehavior = /** @class */ (function () {
  99054. function FramingBehavior() {
  99055. this._mode = FramingBehavior.FitFrustumSidesMode;
  99056. this._radiusScale = 1.0;
  99057. this._positionScale = 0.5;
  99058. this._defaultElevation = 0.3;
  99059. this._elevationReturnTime = 1500;
  99060. this._elevationReturnWaitTime = 1000;
  99061. this._zoomStopsAnimation = false;
  99062. this._framingTime = 1500;
  99063. this._isPointerDown = false;
  99064. this._lastInteractionTime = -Infinity;
  99065. // Framing control
  99066. this._animatables = new Array();
  99067. this._betaIsAnimating = false;
  99068. }
  99069. Object.defineProperty(FramingBehavior.prototype, "name", {
  99070. get: function () {
  99071. return "Framing";
  99072. },
  99073. enumerable: true,
  99074. configurable: true
  99075. });
  99076. Object.defineProperty(FramingBehavior.prototype, "mode", {
  99077. /**
  99078. * Gets current mode used by the behavior.
  99079. */
  99080. get: function () {
  99081. return this._mode;
  99082. },
  99083. /**
  99084. * Sets the current mode used by the behavior
  99085. */
  99086. set: function (mode) {
  99087. this._mode = mode;
  99088. },
  99089. enumerable: true,
  99090. configurable: true
  99091. });
  99092. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  99093. /**
  99094. * Gets the scale applied to the radius
  99095. */
  99096. get: function () {
  99097. return this._radiusScale;
  99098. },
  99099. /**
  99100. * Sets the scale applied to the radius (1 by default)
  99101. */
  99102. set: function (radius) {
  99103. this._radiusScale = radius;
  99104. },
  99105. enumerable: true,
  99106. configurable: true
  99107. });
  99108. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  99109. /**
  99110. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99111. */
  99112. get: function () {
  99113. return this._positionScale;
  99114. },
  99115. /**
  99116. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  99117. */
  99118. set: function (scale) {
  99119. this._positionScale = scale;
  99120. },
  99121. enumerable: true,
  99122. configurable: true
  99123. });
  99124. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  99125. /**
  99126. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99127. * behaviour is triggered, in radians.
  99128. */
  99129. get: function () {
  99130. return this._defaultElevation;
  99131. },
  99132. /**
  99133. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  99134. * behaviour is triggered, in radians.
  99135. */
  99136. set: function (elevation) {
  99137. this._defaultElevation = elevation;
  99138. },
  99139. enumerable: true,
  99140. configurable: true
  99141. });
  99142. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  99143. /**
  99144. * Gets the time (in milliseconds) taken to return to the default beta position.
  99145. * Negative value indicates camera should not return to default.
  99146. */
  99147. get: function () {
  99148. return this._elevationReturnTime;
  99149. },
  99150. /**
  99151. * Sets the time (in milliseconds) taken to return to the default beta position.
  99152. * Negative value indicates camera should not return to default.
  99153. */
  99154. set: function (speed) {
  99155. this._elevationReturnTime = speed;
  99156. },
  99157. enumerable: true,
  99158. configurable: true
  99159. });
  99160. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  99161. /**
  99162. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99163. */
  99164. get: function () {
  99165. return this._elevationReturnWaitTime;
  99166. },
  99167. /**
  99168. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  99169. */
  99170. set: function (time) {
  99171. this._elevationReturnWaitTime = time;
  99172. },
  99173. enumerable: true,
  99174. configurable: true
  99175. });
  99176. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  99177. /**
  99178. * Gets the flag that indicates if user zooming should stop animation.
  99179. */
  99180. get: function () {
  99181. return this._zoomStopsAnimation;
  99182. },
  99183. /**
  99184. * Sets the flag that indicates if user zooming should stop animation.
  99185. */
  99186. set: function (flag) {
  99187. this._zoomStopsAnimation = flag;
  99188. },
  99189. enumerable: true,
  99190. configurable: true
  99191. });
  99192. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  99193. /**
  99194. * Gets the transition time when framing the mesh, in milliseconds
  99195. */
  99196. get: function () {
  99197. return this._framingTime;
  99198. },
  99199. /**
  99200. * Sets the transition time when framing the mesh, in milliseconds
  99201. */
  99202. set: function (time) {
  99203. this._framingTime = time;
  99204. },
  99205. enumerable: true,
  99206. configurable: true
  99207. });
  99208. FramingBehavior.prototype.init = function () {
  99209. // Do notihng
  99210. };
  99211. FramingBehavior.prototype.attach = function (camera) {
  99212. var _this = this;
  99213. this._attachedCamera = camera;
  99214. var scene = this._attachedCamera.getScene();
  99215. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  99216. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99217. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99218. _this._isPointerDown = true;
  99219. return;
  99220. }
  99221. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99222. _this._isPointerDown = false;
  99223. }
  99224. });
  99225. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99226. if (mesh) {
  99227. _this.zoomOnMesh(mesh);
  99228. }
  99229. });
  99230. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99231. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99232. _this._applyUserInteraction();
  99233. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  99234. // back to the default position after a given timeout
  99235. _this._maintainCameraAboveGround();
  99236. });
  99237. };
  99238. FramingBehavior.prototype.detach = function () {
  99239. if (!this._attachedCamera) {
  99240. return;
  99241. }
  99242. var scene = this._attachedCamera.getScene();
  99243. if (this._onPrePointerObservableObserver) {
  99244. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99245. }
  99246. if (this._onAfterCheckInputsObserver) {
  99247. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99248. }
  99249. if (this._onMeshTargetChangedObserver) {
  99250. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99251. }
  99252. this._attachedCamera = null;
  99253. };
  99254. /**
  99255. * Targets the given mesh and updates zoom level accordingly.
  99256. * @param mesh The mesh to target.
  99257. * @param radius Optional. If a cached radius position already exists, overrides default.
  99258. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99259. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99260. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99261. */
  99262. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99263. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99264. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99265. mesh.computeWorldMatrix(true);
  99266. var boundingBox = mesh.getBoundingInfo().boundingBox;
  99267. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  99268. };
  99269. /**
  99270. * Targets the given mesh with its children and updates zoom level accordingly.
  99271. * @param mesh The mesh to target.
  99272. * @param radius Optional. If a cached radius position already exists, overrides default.
  99273. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99274. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99275. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99276. */
  99277. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  99278. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99279. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99280. mesh.computeWorldMatrix(true);
  99281. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  99282. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  99283. };
  99284. /**
  99285. * Targets the given meshes with their children and updates zoom level accordingly.
  99286. * @param meshes The mesh to target.
  99287. * @param radius Optional. If a cached radius position already exists, overrides default.
  99288. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99289. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99290. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99291. */
  99292. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  99293. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99294. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99295. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  99296. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  99297. for (var i = 0; i < meshes.length; i++) {
  99298. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  99299. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  99300. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  99301. }
  99302. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  99303. };
  99304. /**
  99305. * Targets the given mesh and updates zoom level accordingly.
  99306. * @param mesh The mesh to target.
  99307. * @param radius Optional. If a cached radius position already exists, overrides default.
  99308. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  99309. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  99310. * @param onAnimationEnd Callback triggered at the end of the framing animation
  99311. */
  99312. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  99313. var _this = this;
  99314. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  99315. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  99316. var zoomTarget;
  99317. if (!this._attachedCamera) {
  99318. return;
  99319. }
  99320. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  99321. var bottom = minimumWorld.y;
  99322. var top = maximumWorld.y;
  99323. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  99324. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  99325. if (focusOnOriginXZ) {
  99326. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  99327. }
  99328. else {
  99329. var centerWorld = minimumWorld.add(radiusWorld);
  99330. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  99331. }
  99332. if (!this._vectorTransition) {
  99333. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  99334. }
  99335. this._betaIsAnimating = true;
  99336. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  99337. if (animatable) {
  99338. this._animatables.push(animatable);
  99339. }
  99340. // sets the radius and lower radius bounds
  99341. // Small delta ensures camera is not always at lower zoom limit.
  99342. var radius = 0;
  99343. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  99344. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99345. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  99346. radius = position;
  99347. }
  99348. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99349. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  99350. if (this._attachedCamera.lowerRadiusLimit === null) {
  99351. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  99352. }
  99353. }
  99354. // Set sensibilities
  99355. var extend = maximumWorld.subtract(minimumWorld).length();
  99356. this._attachedCamera.panningSensibility = 5000 / extend;
  99357. this._attachedCamera.wheelPrecision = 100 / radius;
  99358. // transition to new radius
  99359. if (!this._radiusTransition) {
  99360. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99361. }
  99362. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  99363. _this.stopAllAnimations();
  99364. if (onAnimationEnd) {
  99365. onAnimationEnd();
  99366. }
  99367. if (_this._attachedCamera) {
  99368. _this._attachedCamera.storeState();
  99369. }
  99370. });
  99371. if (animatable) {
  99372. this._animatables.push(animatable);
  99373. }
  99374. };
  99375. /**
  99376. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  99377. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  99378. * frustum width.
  99379. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  99380. * to fully enclose the mesh in the viewing frustum.
  99381. */
  99382. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  99383. var size = maximumWorld.subtract(minimumWorld);
  99384. var boxVectorGlobalDiagonal = size.length();
  99385. var frustumSlope = this._getFrustumSlope();
  99386. // Formula for setting distance
  99387. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  99388. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  99389. // Horizon distance
  99390. var radius = radiusWithoutFraming * this._radiusScale;
  99391. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  99392. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  99393. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  99394. var camera = this._attachedCamera;
  99395. if (!camera) {
  99396. return 0;
  99397. }
  99398. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  99399. // Don't exceed the requested limit
  99400. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  99401. }
  99402. // Don't exceed the upper radius limit
  99403. if (camera.upperRadiusLimit) {
  99404. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  99405. }
  99406. return distance;
  99407. };
  99408. /**
  99409. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  99410. * is automatically returned to its default position (expected to be above ground plane).
  99411. */
  99412. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  99413. var _this = this;
  99414. if (this._elevationReturnTime < 0) {
  99415. return;
  99416. }
  99417. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  99418. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  99419. var limitBeta = Math.PI * 0.5;
  99420. // Bring the camera back up if below the ground plane
  99421. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  99422. this._betaIsAnimating = true;
  99423. //Transition to new position
  99424. this.stopAllAnimations();
  99425. if (!this._betaTransition) {
  99426. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99427. }
  99428. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  99429. _this._clearAnimationLocks();
  99430. _this.stopAllAnimations();
  99431. });
  99432. if (animatabe) {
  99433. this._animatables.push(animatabe);
  99434. }
  99435. }
  99436. };
  99437. /**
  99438. * Returns the frustum slope based on the canvas ratio and camera FOV
  99439. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  99440. */
  99441. FramingBehavior.prototype._getFrustumSlope = function () {
  99442. // Calculate the viewport ratio
  99443. // Aspect Ratio is Height/Width.
  99444. var camera = this._attachedCamera;
  99445. if (!camera) {
  99446. return BABYLON.Vector2.Zero();
  99447. }
  99448. var engine = camera.getScene().getEngine();
  99449. var aspectRatio = engine.getAspectRatio(camera);
  99450. // Camera FOV is the vertical field of view (top-bottom) in radians.
  99451. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  99452. var frustumSlopeY = Math.tan(camera.fov / 2);
  99453. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  99454. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  99455. // along the forward vector.
  99456. var frustumSlopeX = frustumSlopeY * aspectRatio;
  99457. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  99458. };
  99459. /**
  99460. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  99461. */
  99462. FramingBehavior.prototype._clearAnimationLocks = function () {
  99463. this._betaIsAnimating = false;
  99464. };
  99465. /**
  99466. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99467. */
  99468. FramingBehavior.prototype._applyUserInteraction = function () {
  99469. if (this.isUserIsMoving) {
  99470. this._lastInteractionTime = BABYLON.Tools.Now;
  99471. this.stopAllAnimations();
  99472. this._clearAnimationLocks();
  99473. }
  99474. };
  99475. /**
  99476. * Stops and removes all animations that have been applied to the camera
  99477. */
  99478. FramingBehavior.prototype.stopAllAnimations = function () {
  99479. if (this._attachedCamera) {
  99480. this._attachedCamera.animations = [];
  99481. }
  99482. while (this._animatables.length) {
  99483. if (this._animatables[0]) {
  99484. this._animatables[0].onAnimationEnd = null;
  99485. this._animatables[0].stop();
  99486. }
  99487. this._animatables.shift();
  99488. }
  99489. };
  99490. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  99491. /**
  99492. * Gets a value indicating if the user is moving the camera
  99493. */
  99494. get: function () {
  99495. if (!this._attachedCamera) {
  99496. return false;
  99497. }
  99498. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99499. this._attachedCamera.inertialBetaOffset !== 0 ||
  99500. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99501. this._attachedCamera.inertialPanningX !== 0 ||
  99502. this._attachedCamera.inertialPanningY !== 0 ||
  99503. this._isPointerDown;
  99504. },
  99505. enumerable: true,
  99506. configurable: true
  99507. });
  99508. /**
  99509. * The easing function used by animations
  99510. */
  99511. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  99512. /**
  99513. * The easing mode used by animations
  99514. */
  99515. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  99516. // Statics
  99517. /**
  99518. * The camera can move all the way towards the mesh.
  99519. */
  99520. FramingBehavior.IgnoreBoundsSizeMode = 0;
  99521. /**
  99522. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  99523. */
  99524. FramingBehavior.FitFrustumSidesMode = 1;
  99525. return FramingBehavior;
  99526. }());
  99527. BABYLON.FramingBehavior = FramingBehavior;
  99528. })(BABYLON || (BABYLON = {}));
  99529. //# sourceMappingURL=babylon.framingBehavior.js.map
  99530. var BABYLON;
  99531. (function (BABYLON) {
  99532. /**
  99533. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  99534. */
  99535. var BouncingBehavior = /** @class */ (function () {
  99536. function BouncingBehavior() {
  99537. /**
  99538. * The duration of the animation, in milliseconds
  99539. */
  99540. this.transitionDuration = 450;
  99541. /**
  99542. * Length of the distance animated by the transition when lower radius is reached
  99543. */
  99544. this.lowerRadiusTransitionRange = 2;
  99545. /**
  99546. * Length of the distance animated by the transition when upper radius is reached
  99547. */
  99548. this.upperRadiusTransitionRange = -2;
  99549. this._autoTransitionRange = false;
  99550. // Animations
  99551. this._radiusIsAnimating = false;
  99552. this._radiusBounceTransition = null;
  99553. this._animatables = new Array();
  99554. }
  99555. Object.defineProperty(BouncingBehavior.prototype, "name", {
  99556. get: function () {
  99557. return "Bouncing";
  99558. },
  99559. enumerable: true,
  99560. configurable: true
  99561. });
  99562. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  99563. /**
  99564. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99565. */
  99566. get: function () {
  99567. return this._autoTransitionRange;
  99568. },
  99569. /**
  99570. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99571. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  99572. */
  99573. set: function (value) {
  99574. var _this = this;
  99575. if (this._autoTransitionRange === value) {
  99576. return;
  99577. }
  99578. this._autoTransitionRange = value;
  99579. var camera = this._attachedCamera;
  99580. if (!camera) {
  99581. return;
  99582. }
  99583. if (value) {
  99584. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99585. if (!mesh) {
  99586. return;
  99587. }
  99588. mesh.computeWorldMatrix(true);
  99589. var diagonal = mesh.getBoundingInfo().diagonalLength;
  99590. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  99591. _this.upperRadiusTransitionRange = diagonal * 0.05;
  99592. });
  99593. }
  99594. else if (this._onMeshTargetChangedObserver) {
  99595. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99596. }
  99597. },
  99598. enumerable: true,
  99599. configurable: true
  99600. });
  99601. BouncingBehavior.prototype.init = function () {
  99602. // Do notihng
  99603. };
  99604. BouncingBehavior.prototype.attach = function (camera) {
  99605. var _this = this;
  99606. this._attachedCamera = camera;
  99607. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99608. if (!_this._attachedCamera) {
  99609. return;
  99610. }
  99611. // Add the bounce animation to the lower radius limit
  99612. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  99613. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  99614. }
  99615. // Add the bounce animation to the upper radius limit
  99616. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  99617. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  99618. }
  99619. });
  99620. };
  99621. BouncingBehavior.prototype.detach = function () {
  99622. if (!this._attachedCamera) {
  99623. return;
  99624. }
  99625. if (this._onAfterCheckInputsObserver) {
  99626. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99627. }
  99628. if (this._onMeshTargetChangedObserver) {
  99629. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99630. }
  99631. this._attachedCamera = null;
  99632. };
  99633. /**
  99634. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  99635. * @param radiusLimit The limit to check against.
  99636. * @return Bool to indicate if at limit.
  99637. */
  99638. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  99639. if (!this._attachedCamera) {
  99640. return false;
  99641. }
  99642. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  99643. return true;
  99644. }
  99645. return false;
  99646. };
  99647. /**
  99648. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  99649. * @param radiusDelta The delta by which to animate to. Can be negative.
  99650. */
  99651. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  99652. var _this = this;
  99653. if (!this._attachedCamera) {
  99654. return;
  99655. }
  99656. if (!this._radiusBounceTransition) {
  99657. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  99658. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  99659. }
  99660. // Prevent zoom until bounce has completed
  99661. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  99662. this._attachedCamera.wheelPrecision = Infinity;
  99663. this._attachedCamera.inertialRadiusOffset = 0;
  99664. // Animate to the radius limit
  99665. this.stopAllAnimations();
  99666. this._radiusIsAnimating = true;
  99667. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  99668. if (animatable) {
  99669. this._animatables.push(animatable);
  99670. }
  99671. };
  99672. /**
  99673. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  99674. */
  99675. BouncingBehavior.prototype._clearAnimationLocks = function () {
  99676. this._radiusIsAnimating = false;
  99677. if (this._attachedCamera) {
  99678. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  99679. }
  99680. };
  99681. /**
  99682. * Stops and removes all animations that have been applied to the camera
  99683. */
  99684. BouncingBehavior.prototype.stopAllAnimations = function () {
  99685. if (this._attachedCamera) {
  99686. this._attachedCamera.animations = [];
  99687. }
  99688. while (this._animatables.length) {
  99689. this._animatables[0].onAnimationEnd = null;
  99690. this._animatables[0].stop();
  99691. this._animatables.shift();
  99692. }
  99693. };
  99694. /**
  99695. * The easing function used by animations
  99696. */
  99697. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  99698. /**
  99699. * The easing mode used by animations
  99700. */
  99701. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  99702. return BouncingBehavior;
  99703. }());
  99704. BABYLON.BouncingBehavior = BouncingBehavior;
  99705. })(BABYLON || (BABYLON = {}));
  99706. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  99707. var BABYLON;
  99708. (function (BABYLON) {
  99709. var AutoRotationBehavior = /** @class */ (function () {
  99710. function AutoRotationBehavior() {
  99711. this._zoomStopsAnimation = false;
  99712. this._idleRotationSpeed = 0.05;
  99713. this._idleRotationWaitTime = 2000;
  99714. this._idleRotationSpinupTime = 2000;
  99715. this._isPointerDown = false;
  99716. this._lastFrameTime = null;
  99717. this._lastInteractionTime = -Infinity;
  99718. this._cameraRotationSpeed = 0;
  99719. this._lastFrameRadius = 0;
  99720. }
  99721. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  99722. get: function () {
  99723. return "AutoRotation";
  99724. },
  99725. enumerable: true,
  99726. configurable: true
  99727. });
  99728. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  99729. /**
  99730. * Gets the flag that indicates if user zooming should stop animation.
  99731. */
  99732. get: function () {
  99733. return this._zoomStopsAnimation;
  99734. },
  99735. /**
  99736. * Sets the flag that indicates if user zooming should stop animation.
  99737. */
  99738. set: function (flag) {
  99739. this._zoomStopsAnimation = flag;
  99740. },
  99741. enumerable: true,
  99742. configurable: true
  99743. });
  99744. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  99745. /**
  99746. * Gets the default speed at which the camera rotates around the model.
  99747. */
  99748. get: function () {
  99749. return this._idleRotationSpeed;
  99750. },
  99751. /**
  99752. * Sets the default speed at which the camera rotates around the model.
  99753. */
  99754. set: function (speed) {
  99755. this._idleRotationSpeed = speed;
  99756. },
  99757. enumerable: true,
  99758. configurable: true
  99759. });
  99760. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  99761. /**
  99762. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  99763. */
  99764. get: function () {
  99765. return this._idleRotationWaitTime;
  99766. },
  99767. /**
  99768. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  99769. */
  99770. set: function (time) {
  99771. this._idleRotationWaitTime = time;
  99772. },
  99773. enumerable: true,
  99774. configurable: true
  99775. });
  99776. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  99777. /**
  99778. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  99779. */
  99780. get: function () {
  99781. return this._idleRotationSpinupTime;
  99782. },
  99783. /**
  99784. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  99785. */
  99786. set: function (time) {
  99787. this._idleRotationSpinupTime = time;
  99788. },
  99789. enumerable: true,
  99790. configurable: true
  99791. });
  99792. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  99793. /**
  99794. * Gets a value indicating if the camera is currently rotating because of this behavior
  99795. */
  99796. get: function () {
  99797. return Math.abs(this._cameraRotationSpeed) > 0;
  99798. },
  99799. enumerable: true,
  99800. configurable: true
  99801. });
  99802. AutoRotationBehavior.prototype.init = function () {
  99803. // Do notihng
  99804. };
  99805. AutoRotationBehavior.prototype.attach = function (camera) {
  99806. var _this = this;
  99807. this._attachedCamera = camera;
  99808. var scene = this._attachedCamera.getScene();
  99809. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99810. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99811. _this._isPointerDown = true;
  99812. return;
  99813. }
  99814. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99815. _this._isPointerDown = false;
  99816. }
  99817. });
  99818. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99819. var now = BABYLON.Tools.Now;
  99820. var dt = 0;
  99821. if (_this._lastFrameTime != null) {
  99822. dt = now - _this._lastFrameTime;
  99823. }
  99824. _this._lastFrameTime = now;
  99825. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99826. _this._applyUserInteraction();
  99827. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  99828. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  99829. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  99830. // Step camera rotation by rotation speed
  99831. if (_this._attachedCamera) {
  99832. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  99833. }
  99834. });
  99835. };
  99836. AutoRotationBehavior.prototype.detach = function () {
  99837. if (!this._attachedCamera) {
  99838. return;
  99839. }
  99840. var scene = this._attachedCamera.getScene();
  99841. if (this._onPrePointerObservableObserver) {
  99842. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99843. }
  99844. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99845. this._attachedCamera = null;
  99846. };
  99847. /**
  99848. * Returns true if user is scrolling.
  99849. * @return true if user is scrolling.
  99850. */
  99851. AutoRotationBehavior.prototype._userIsZooming = function () {
  99852. if (!this._attachedCamera) {
  99853. return false;
  99854. }
  99855. return this._attachedCamera.inertialRadiusOffset !== 0;
  99856. };
  99857. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  99858. if (!this._attachedCamera) {
  99859. return false;
  99860. }
  99861. var zoomHasHitLimit = false;
  99862. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  99863. zoomHasHitLimit = true;
  99864. }
  99865. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  99866. this._lastFrameRadius = this._attachedCamera.radius;
  99867. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  99868. };
  99869. /**
  99870. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99871. */
  99872. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  99873. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  99874. this._lastInteractionTime = BABYLON.Tools.Now;
  99875. }
  99876. };
  99877. // Tools
  99878. AutoRotationBehavior.prototype._userIsMoving = function () {
  99879. if (!this._attachedCamera) {
  99880. return false;
  99881. }
  99882. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99883. this._attachedCamera.inertialBetaOffset !== 0 ||
  99884. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99885. this._attachedCamera.inertialPanningX !== 0 ||
  99886. this._attachedCamera.inertialPanningY !== 0 ||
  99887. this._isPointerDown;
  99888. };
  99889. return AutoRotationBehavior;
  99890. }());
  99891. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  99892. })(BABYLON || (BABYLON = {}));
  99893. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  99894. var BABYLON;
  99895. (function (BABYLON) {
  99896. var NullEngineOptions = /** @class */ (function () {
  99897. function NullEngineOptions() {
  99898. this.renderWidth = 512;
  99899. this.renderHeight = 256;
  99900. this.textureSize = 512;
  99901. this.deterministicLockstep = false;
  99902. this.lockstepMaxSteps = 4;
  99903. }
  99904. return NullEngineOptions;
  99905. }());
  99906. BABYLON.NullEngineOptions = NullEngineOptions;
  99907. /**
  99908. * The null engine class provides support for headless version of babylon.js.
  99909. * This can be used in server side scenario or for testing purposes
  99910. */
  99911. var NullEngine = /** @class */ (function (_super) {
  99912. __extends(NullEngine, _super);
  99913. function NullEngine(options) {
  99914. if (options === void 0) { options = new NullEngineOptions(); }
  99915. var _this = _super.call(this, null) || this;
  99916. if (options.deterministicLockstep === undefined) {
  99917. options.deterministicLockstep = false;
  99918. }
  99919. if (options.lockstepMaxSteps === undefined) {
  99920. options.lockstepMaxSteps = 4;
  99921. }
  99922. _this._options = options;
  99923. // Init caps
  99924. // We consider we are on a webgl1 capable device
  99925. _this._caps = new BABYLON.EngineCapabilities();
  99926. _this._caps.maxTexturesImageUnits = 16;
  99927. _this._caps.maxVertexTextureImageUnits = 16;
  99928. _this._caps.maxTextureSize = 512;
  99929. _this._caps.maxCubemapTextureSize = 512;
  99930. _this._caps.maxRenderTextureSize = 512;
  99931. _this._caps.maxVertexAttribs = 16;
  99932. _this._caps.maxVaryingVectors = 16;
  99933. _this._caps.maxFragmentUniformVectors = 16;
  99934. _this._caps.maxVertexUniformVectors = 16;
  99935. // Extensions
  99936. _this._caps.standardDerivatives = false;
  99937. _this._caps.astc = null;
  99938. _this._caps.s3tc = null;
  99939. _this._caps.pvrtc = null;
  99940. _this._caps.etc1 = null;
  99941. _this._caps.etc2 = null;
  99942. _this._caps.textureAnisotropicFilterExtension = null;
  99943. _this._caps.maxAnisotropy = 0;
  99944. _this._caps.uintIndices = false;
  99945. _this._caps.fragmentDepthSupported = false;
  99946. _this._caps.highPrecisionShaderSupported = true;
  99947. _this._caps.colorBufferFloat = false;
  99948. _this._caps.textureFloat = false;
  99949. _this._caps.textureFloatLinearFiltering = false;
  99950. _this._caps.textureFloatRender = false;
  99951. _this._caps.textureHalfFloat = false;
  99952. _this._caps.textureHalfFloatLinearFiltering = false;
  99953. _this._caps.textureHalfFloatRender = false;
  99954. _this._caps.textureLOD = false;
  99955. _this._caps.drawBuffersExtension = false;
  99956. _this._caps.depthTextureExtension = false;
  99957. _this._caps.vertexArrayObject = false;
  99958. _this._caps.instancedArrays = false;
  99959. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  99960. // Wrappers
  99961. if (typeof URL === "undefined") {
  99962. URL = {
  99963. createObjectURL: function () { },
  99964. revokeObjectURL: function () { }
  99965. };
  99966. }
  99967. if (typeof Blob === "undefined") {
  99968. Blob = function () { };
  99969. }
  99970. return _this;
  99971. }
  99972. NullEngine.prototype.isDeterministicLockStep = function () {
  99973. return this._options.deterministicLockstep;
  99974. };
  99975. NullEngine.prototype.getLockstepMaxSteps = function () {
  99976. return this._options.lockstepMaxSteps;
  99977. };
  99978. NullEngine.prototype.getHardwareScalingLevel = function () {
  99979. return 1.0;
  99980. };
  99981. NullEngine.prototype.createVertexBuffer = function (vertices) {
  99982. return {
  99983. capacity: 0,
  99984. references: 1,
  99985. is32Bits: false
  99986. };
  99987. };
  99988. NullEngine.prototype.createIndexBuffer = function (indices) {
  99989. return {
  99990. capacity: 0,
  99991. references: 1,
  99992. is32Bits: false
  99993. };
  99994. };
  99995. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  99996. if (stencil === void 0) { stencil = false; }
  99997. };
  99998. NullEngine.prototype.getRenderWidth = function (useScreen) {
  99999. if (useScreen === void 0) { useScreen = false; }
  100000. if (!useScreen && this._currentRenderTarget) {
  100001. return this._currentRenderTarget.width;
  100002. }
  100003. return this._options.renderWidth;
  100004. };
  100005. NullEngine.prototype.getRenderHeight = function (useScreen) {
  100006. if (useScreen === void 0) { useScreen = false; }
  100007. if (!useScreen && this._currentRenderTarget) {
  100008. return this._currentRenderTarget.height;
  100009. }
  100010. return this._options.renderHeight;
  100011. };
  100012. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  100013. this._cachedViewport = viewport;
  100014. };
  100015. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  100016. return {
  100017. transformFeedback: null,
  100018. __SPECTOR_rebuildProgram: null
  100019. };
  100020. };
  100021. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  100022. return [];
  100023. };
  100024. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  100025. return [];
  100026. };
  100027. NullEngine.prototype.bindSamplers = function (effect) {
  100028. this._currentEffect = null;
  100029. };
  100030. NullEngine.prototype.enableEffect = function (effect) {
  100031. this._currentEffect = effect;
  100032. if (effect.onBind) {
  100033. effect.onBind(effect);
  100034. }
  100035. effect.onBindObservable.notifyObservers(effect);
  100036. };
  100037. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  100038. if (zOffset === void 0) { zOffset = 0; }
  100039. if (reverseSide === void 0) { reverseSide = false; }
  100040. };
  100041. NullEngine.prototype.setIntArray = function (uniform, array) {
  100042. };
  100043. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  100044. };
  100045. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  100046. };
  100047. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  100048. };
  100049. NullEngine.prototype.setFloatArray = function (uniform, array) {
  100050. };
  100051. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  100052. };
  100053. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  100054. };
  100055. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  100056. };
  100057. NullEngine.prototype.setArray = function (uniform, array) {
  100058. };
  100059. NullEngine.prototype.setArray2 = function (uniform, array) {
  100060. };
  100061. NullEngine.prototype.setArray3 = function (uniform, array) {
  100062. };
  100063. NullEngine.prototype.setArray4 = function (uniform, array) {
  100064. };
  100065. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  100066. };
  100067. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  100068. };
  100069. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  100070. };
  100071. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  100072. };
  100073. NullEngine.prototype.setFloat = function (uniform, value) {
  100074. };
  100075. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  100076. };
  100077. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  100078. };
  100079. NullEngine.prototype.setBool = function (uniform, bool) {
  100080. };
  100081. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  100082. };
  100083. NullEngine.prototype.setColor3 = function (uniform, color3) {
  100084. };
  100085. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  100086. };
  100087. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  100088. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  100089. if (this._alphaMode === mode) {
  100090. return;
  100091. }
  100092. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  100093. if (!noDepthWriteChange) {
  100094. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  100095. }
  100096. this._alphaMode = mode;
  100097. };
  100098. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  100099. };
  100100. NullEngine.prototype.wipeCaches = function (bruteForce) {
  100101. if (this.preventCacheWipeBetweenFrames) {
  100102. return;
  100103. }
  100104. this.resetTextureCache();
  100105. this._currentEffect = null;
  100106. if (bruteForce) {
  100107. this._currentProgram = null;
  100108. this._stencilState.reset();
  100109. this._depthCullingState.reset();
  100110. this._alphaState.reset();
  100111. }
  100112. this._cachedVertexBuffers = null;
  100113. this._cachedIndexBuffer = null;
  100114. this._cachedEffectForVertexBuffers = null;
  100115. };
  100116. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  100117. };
  100118. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  100119. };
  100120. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  100121. };
  100122. NullEngine.prototype._createTexture = function () {
  100123. return {};
  100124. };
  100125. NullEngine.prototype._releaseTexture = function (texture) {
  100126. };
  100127. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  100128. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  100129. if (onLoad === void 0) { onLoad = null; }
  100130. if (onError === void 0) { onError = null; }
  100131. if (buffer === void 0) { buffer = null; }
  100132. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  100133. var url = String(urlArg);
  100134. texture.url = url;
  100135. texture.generateMipMaps = !noMipmap;
  100136. texture.samplingMode = samplingMode;
  100137. texture.invertY = invertY;
  100138. texture.baseWidth = this._options.textureSize;
  100139. texture.baseHeight = this._options.textureSize;
  100140. texture.width = this._options.textureSize;
  100141. texture.height = this._options.textureSize;
  100142. if (format) {
  100143. texture.format = format;
  100144. }
  100145. texture.isReady = true;
  100146. if (onLoad) {
  100147. onLoad();
  100148. }
  100149. this._internalTexturesCache.push(texture);
  100150. return texture;
  100151. };
  100152. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  100153. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  100154. if (options !== undefined && typeof options === "object") {
  100155. fullOptions.generateMipMaps = options.generateMipMaps;
  100156. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  100157. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  100158. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  100159. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  100160. }
  100161. else {
  100162. fullOptions.generateMipMaps = options;
  100163. fullOptions.generateDepthBuffer = true;
  100164. fullOptions.generateStencilBuffer = false;
  100165. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  100166. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  100167. }
  100168. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  100169. var width = size.width || size;
  100170. var height = size.height || size;
  100171. texture._depthStencilBuffer = {};
  100172. texture._framebuffer = {};
  100173. texture.baseWidth = width;
  100174. texture.baseHeight = height;
  100175. texture.width = width;
  100176. texture.height = height;
  100177. texture.isReady = true;
  100178. texture.samples = 1;
  100179. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  100180. texture.samplingMode = fullOptions.samplingMode;
  100181. texture.type = fullOptions.type;
  100182. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  100183. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  100184. this._internalTexturesCache.push(texture);
  100185. return texture;
  100186. };
  100187. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  100188. texture.samplingMode = samplingMode;
  100189. };
  100190. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  100191. if (this._currentRenderTarget) {
  100192. this.unBindFramebuffer(this._currentRenderTarget);
  100193. }
  100194. this._currentRenderTarget = texture;
  100195. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  100196. if (this._cachedViewport && !forceFullscreenViewport) {
  100197. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  100198. }
  100199. };
  100200. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  100201. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  100202. this._currentRenderTarget = null;
  100203. if (onBeforeUnbind) {
  100204. if (texture._MSAAFramebuffer) {
  100205. this._currentFramebuffer = texture._framebuffer;
  100206. }
  100207. onBeforeUnbind();
  100208. }
  100209. this._currentFramebuffer = null;
  100210. };
  100211. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  100212. var vbo = {
  100213. capacity: 1,
  100214. references: 1,
  100215. is32Bits: false
  100216. };
  100217. return vbo;
  100218. };
  100219. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  100220. if (premulAlpha === void 0) { premulAlpha = false; }
  100221. };
  100222. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  100223. if (offset === void 0) { offset = 0; }
  100224. };
  100225. /**
  100226. * Updates a dynamic vertex buffer.
  100227. * @param vertexBuffer the vertex buffer to update
  100228. * @param data the data used to update the vertex buffer
  100229. * @param byteOffset the byte offset of the data (optional)
  100230. * @param byteLength the byte length of the data (optional)
  100231. */
  100232. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  100233. };
  100234. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  100235. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  100236. this._boundTexturesCache[this._activeChannel] = texture;
  100237. return true;
  100238. }
  100239. return false;
  100240. };
  100241. NullEngine.prototype._bindTexture = function (channel, texture) {
  100242. if (channel < 0) {
  100243. return;
  100244. }
  100245. this._bindTextureDirectly(0, texture);
  100246. };
  100247. NullEngine.prototype._releaseBuffer = function (buffer) {
  100248. buffer.references--;
  100249. if (buffer.references === 0) {
  100250. return true;
  100251. }
  100252. return false;
  100253. };
  100254. NullEngine.prototype.releaseEffects = function () {
  100255. };
  100256. NullEngine.prototype.displayLoadingUI = function () {
  100257. };
  100258. NullEngine.prototype.hideLoadingUI = function () {
  100259. };
  100260. return NullEngine;
  100261. }(BABYLON.Engine));
  100262. BABYLON.NullEngine = NullEngine;
  100263. })(BABYLON || (BABYLON = {}));
  100264. //# sourceMappingURL=babylon.nullEngine.js.map
  100265. var BABYLON;
  100266. (function (BABYLON) {
  100267. /**
  100268. * This class can be used to get instrumentation data from a Babylon engine
  100269. */
  100270. var EngineInstrumentation = /** @class */ (function () {
  100271. function EngineInstrumentation(engine) {
  100272. this.engine = engine;
  100273. this._captureGPUFrameTime = false;
  100274. this._gpuFrameTime = new BABYLON.PerfCounter();
  100275. this._captureShaderCompilationTime = false;
  100276. this._shaderCompilationTime = new BABYLON.PerfCounter();
  100277. // Observers
  100278. this._onBeginFrameObserver = null;
  100279. this._onEndFrameObserver = null;
  100280. this._onBeforeShaderCompilationObserver = null;
  100281. this._onAfterShaderCompilationObserver = null;
  100282. }
  100283. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  100284. // Properties
  100285. /**
  100286. * Gets the perf counter used for GPU frame time
  100287. */
  100288. get: function () {
  100289. return this._gpuFrameTime;
  100290. },
  100291. enumerable: true,
  100292. configurable: true
  100293. });
  100294. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  100295. /**
  100296. * Gets the GPU frame time capture status
  100297. */
  100298. get: function () {
  100299. return this._captureGPUFrameTime;
  100300. },
  100301. /**
  100302. * Enable or disable the GPU frame time capture
  100303. */
  100304. set: function (value) {
  100305. var _this = this;
  100306. if (value === this._captureGPUFrameTime) {
  100307. return;
  100308. }
  100309. this._captureGPUFrameTime = value;
  100310. if (value) {
  100311. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  100312. if (!_this._gpuFrameTimeToken) {
  100313. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  100314. }
  100315. });
  100316. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  100317. if (!_this._gpuFrameTimeToken) {
  100318. return;
  100319. }
  100320. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  100321. if (time > -1) {
  100322. _this._gpuFrameTimeToken = null;
  100323. _this._gpuFrameTime.fetchNewFrame();
  100324. _this._gpuFrameTime.addCount(time, true);
  100325. }
  100326. });
  100327. }
  100328. else {
  100329. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100330. this._onBeginFrameObserver = null;
  100331. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100332. this._onEndFrameObserver = null;
  100333. }
  100334. },
  100335. enumerable: true,
  100336. configurable: true
  100337. });
  100338. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  100339. /**
  100340. * Gets the perf counter used for shader compilation time
  100341. */
  100342. get: function () {
  100343. return this._shaderCompilationTime;
  100344. },
  100345. enumerable: true,
  100346. configurable: true
  100347. });
  100348. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  100349. /**
  100350. * Gets the shader compilation time capture status
  100351. */
  100352. get: function () {
  100353. return this._captureShaderCompilationTime;
  100354. },
  100355. /**
  100356. * Enable or disable the shader compilation time capture
  100357. */
  100358. set: function (value) {
  100359. var _this = this;
  100360. if (value === this._captureShaderCompilationTime) {
  100361. return;
  100362. }
  100363. this._captureShaderCompilationTime = value;
  100364. if (value) {
  100365. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  100366. _this._shaderCompilationTime.fetchNewFrame();
  100367. _this._shaderCompilationTime.beginMonitoring();
  100368. });
  100369. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  100370. _this._shaderCompilationTime.endMonitoring();
  100371. });
  100372. }
  100373. else {
  100374. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100375. this._onBeforeShaderCompilationObserver = null;
  100376. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100377. this._onAfterShaderCompilationObserver = null;
  100378. }
  100379. },
  100380. enumerable: true,
  100381. configurable: true
  100382. });
  100383. EngineInstrumentation.prototype.dispose = function () {
  100384. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  100385. this._onBeginFrameObserver = null;
  100386. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  100387. this._onEndFrameObserver = null;
  100388. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  100389. this._onBeforeShaderCompilationObserver = null;
  100390. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  100391. this._onAfterShaderCompilationObserver = null;
  100392. this.engine = null;
  100393. };
  100394. return EngineInstrumentation;
  100395. }());
  100396. BABYLON.EngineInstrumentation = EngineInstrumentation;
  100397. })(BABYLON || (BABYLON = {}));
  100398. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  100399. var BABYLON;
  100400. (function (BABYLON) {
  100401. /**
  100402. * This class can be used to get instrumentation data from a Babylon engine
  100403. */
  100404. var SceneInstrumentation = /** @class */ (function () {
  100405. function SceneInstrumentation(scene) {
  100406. var _this = this;
  100407. this.scene = scene;
  100408. this._captureActiveMeshesEvaluationTime = false;
  100409. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  100410. this._captureRenderTargetsRenderTime = false;
  100411. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  100412. this._captureFrameTime = false;
  100413. this._frameTime = new BABYLON.PerfCounter();
  100414. this._captureRenderTime = false;
  100415. this._renderTime = new BABYLON.PerfCounter();
  100416. this._captureInterFrameTime = false;
  100417. this._interFrameTime = new BABYLON.PerfCounter();
  100418. this._captureParticlesRenderTime = false;
  100419. this._particlesRenderTime = new BABYLON.PerfCounter();
  100420. this._captureSpritesRenderTime = false;
  100421. this._spritesRenderTime = new BABYLON.PerfCounter();
  100422. this._capturePhysicsTime = false;
  100423. this._physicsTime = new BABYLON.PerfCounter();
  100424. this._captureAnimationsTime = false;
  100425. this._animationsTime = new BABYLON.PerfCounter();
  100426. this._captureCameraRenderTime = false;
  100427. this._cameraRenderTime = new BABYLON.PerfCounter();
  100428. // Observers
  100429. this._onBeforeActiveMeshesEvaluationObserver = null;
  100430. this._onAfterActiveMeshesEvaluationObserver = null;
  100431. this._onBeforeRenderTargetsRenderObserver = null;
  100432. this._onAfterRenderTargetsRenderObserver = null;
  100433. this._onAfterRenderObserver = null;
  100434. this._onBeforeDrawPhaseObserver = null;
  100435. this._onAfterDrawPhaseObserver = null;
  100436. this._onBeforeAnimationsObserver = null;
  100437. this._onBeforeParticlesRenderingObserver = null;
  100438. this._onAfterParticlesRenderingObserver = null;
  100439. this._onBeforeSpritesRenderingObserver = null;
  100440. this._onAfterSpritesRenderingObserver = null;
  100441. this._onBeforePhysicsObserver = null;
  100442. this._onAfterPhysicsObserver = null;
  100443. this._onAfterAnimationsObserver = null;
  100444. this._onBeforeCameraRenderObserver = null;
  100445. this._onAfterCameraRenderObserver = null;
  100446. // Before render
  100447. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  100448. if (_this._captureActiveMeshesEvaluationTime) {
  100449. _this._activeMeshesEvaluationTime.fetchNewFrame();
  100450. }
  100451. if (_this._captureRenderTargetsRenderTime) {
  100452. _this._renderTargetsRenderTime.fetchNewFrame();
  100453. }
  100454. if (_this._captureFrameTime) {
  100455. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  100456. _this._frameTime.beginMonitoring();
  100457. }
  100458. if (_this._captureInterFrameTime) {
  100459. _this._interFrameTime.endMonitoring();
  100460. }
  100461. if (_this._captureParticlesRenderTime) {
  100462. _this._particlesRenderTime.fetchNewFrame();
  100463. }
  100464. if (_this._captureSpritesRenderTime) {
  100465. _this._spritesRenderTime.fetchNewFrame();
  100466. }
  100467. if (_this._captureAnimationsTime) {
  100468. _this._animationsTime.beginMonitoring();
  100469. }
  100470. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  100471. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  100472. });
  100473. // After render
  100474. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  100475. if (_this._captureFrameTime) {
  100476. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  100477. _this._frameTime.endMonitoring();
  100478. }
  100479. if (_this._captureRenderTime) {
  100480. _this._renderTime.endMonitoring(false);
  100481. }
  100482. if (_this._captureInterFrameTime) {
  100483. _this._interFrameTime.beginMonitoring();
  100484. }
  100485. });
  100486. }
  100487. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  100488. // Properties
  100489. /**
  100490. * Gets the perf counter used for active meshes evaluation time
  100491. */
  100492. get: function () {
  100493. return this._activeMeshesEvaluationTime;
  100494. },
  100495. enumerable: true,
  100496. configurable: true
  100497. });
  100498. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  100499. /**
  100500. * Gets the active meshes evaluation time capture status
  100501. */
  100502. get: function () {
  100503. return this._captureActiveMeshesEvaluationTime;
  100504. },
  100505. /**
  100506. * Enable or disable the active meshes evaluation time capture
  100507. */
  100508. set: function (value) {
  100509. var _this = this;
  100510. if (value === this._captureActiveMeshesEvaluationTime) {
  100511. return;
  100512. }
  100513. this._captureActiveMeshesEvaluationTime = value;
  100514. if (value) {
  100515. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  100516. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  100517. _this._activeMeshesEvaluationTime.beginMonitoring();
  100518. });
  100519. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  100520. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  100521. _this._activeMeshesEvaluationTime.endMonitoring();
  100522. });
  100523. }
  100524. else {
  100525. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100526. this._onBeforeActiveMeshesEvaluationObserver = null;
  100527. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100528. this._onAfterActiveMeshesEvaluationObserver = null;
  100529. }
  100530. },
  100531. enumerable: true,
  100532. configurable: true
  100533. });
  100534. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  100535. /**
  100536. * Gets the perf counter used for render targets render time
  100537. */
  100538. get: function () {
  100539. return this._renderTargetsRenderTime;
  100540. },
  100541. enumerable: true,
  100542. configurable: true
  100543. });
  100544. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  100545. /**
  100546. * Gets the render targets render time capture status
  100547. */
  100548. get: function () {
  100549. return this._captureRenderTargetsRenderTime;
  100550. },
  100551. /**
  100552. * Enable or disable the render targets render time capture
  100553. */
  100554. set: function (value) {
  100555. var _this = this;
  100556. if (value === this._captureRenderTargetsRenderTime) {
  100557. return;
  100558. }
  100559. this._captureRenderTargetsRenderTime = value;
  100560. if (value) {
  100561. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  100562. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  100563. _this._renderTargetsRenderTime.beginMonitoring();
  100564. });
  100565. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  100566. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  100567. _this._renderTargetsRenderTime.endMonitoring(false);
  100568. });
  100569. }
  100570. else {
  100571. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100572. this._onBeforeRenderTargetsRenderObserver = null;
  100573. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100574. this._onAfterRenderTargetsRenderObserver = null;
  100575. }
  100576. },
  100577. enumerable: true,
  100578. configurable: true
  100579. });
  100580. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  100581. /**
  100582. * Gets the perf counter used for particles render time
  100583. */
  100584. get: function () {
  100585. return this._particlesRenderTime;
  100586. },
  100587. enumerable: true,
  100588. configurable: true
  100589. });
  100590. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  100591. /**
  100592. * Gets the particles render time capture status
  100593. */
  100594. get: function () {
  100595. return this._captureParticlesRenderTime;
  100596. },
  100597. /**
  100598. * Enable or disable the particles render time capture
  100599. */
  100600. set: function (value) {
  100601. var _this = this;
  100602. if (value === this._captureParticlesRenderTime) {
  100603. return;
  100604. }
  100605. this._captureParticlesRenderTime = value;
  100606. if (value) {
  100607. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  100608. BABYLON.Tools.StartPerformanceCounter("Particles");
  100609. _this._particlesRenderTime.beginMonitoring();
  100610. });
  100611. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  100612. BABYLON.Tools.EndPerformanceCounter("Particles");
  100613. _this._particlesRenderTime.endMonitoring(false);
  100614. });
  100615. }
  100616. else {
  100617. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100618. this._onBeforeParticlesRenderingObserver = null;
  100619. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100620. this._onAfterParticlesRenderingObserver = null;
  100621. }
  100622. },
  100623. enumerable: true,
  100624. configurable: true
  100625. });
  100626. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  100627. /**
  100628. * Gets the perf counter used for sprites render time
  100629. */
  100630. get: function () {
  100631. return this._spritesRenderTime;
  100632. },
  100633. enumerable: true,
  100634. configurable: true
  100635. });
  100636. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  100637. /**
  100638. * Gets the sprites render time capture status
  100639. */
  100640. get: function () {
  100641. return this._captureSpritesRenderTime;
  100642. },
  100643. /**
  100644. * Enable or disable the sprites render time capture
  100645. */
  100646. set: function (value) {
  100647. var _this = this;
  100648. if (value === this._captureSpritesRenderTime) {
  100649. return;
  100650. }
  100651. this._captureSpritesRenderTime = value;
  100652. if (value) {
  100653. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  100654. BABYLON.Tools.StartPerformanceCounter("Sprites");
  100655. _this._spritesRenderTime.beginMonitoring();
  100656. });
  100657. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  100658. BABYLON.Tools.EndPerformanceCounter("Sprites");
  100659. _this._spritesRenderTime.endMonitoring(false);
  100660. });
  100661. }
  100662. else {
  100663. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  100664. this._onBeforeSpritesRenderingObserver = null;
  100665. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  100666. this._onAfterSpritesRenderingObserver = null;
  100667. }
  100668. },
  100669. enumerable: true,
  100670. configurable: true
  100671. });
  100672. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  100673. /**
  100674. * Gets the perf counter used for physics time
  100675. */
  100676. get: function () {
  100677. return this._physicsTime;
  100678. },
  100679. enumerable: true,
  100680. configurable: true
  100681. });
  100682. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  100683. /**
  100684. * Gets the physics time capture status
  100685. */
  100686. get: function () {
  100687. return this._capturePhysicsTime;
  100688. },
  100689. /**
  100690. * Enable or disable the physics time capture
  100691. */
  100692. set: function (value) {
  100693. var _this = this;
  100694. if (value === this._capturePhysicsTime) {
  100695. return;
  100696. }
  100697. this._capturePhysicsTime = value;
  100698. if (value) {
  100699. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  100700. BABYLON.Tools.StartPerformanceCounter("Physics");
  100701. _this._physicsTime.beginMonitoring();
  100702. });
  100703. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  100704. BABYLON.Tools.EndPerformanceCounter("Physics");
  100705. _this._physicsTime.endMonitoring();
  100706. });
  100707. }
  100708. else {
  100709. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  100710. this._onBeforePhysicsObserver = null;
  100711. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  100712. this._onAfterPhysicsObserver = null;
  100713. }
  100714. },
  100715. enumerable: true,
  100716. configurable: true
  100717. });
  100718. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  100719. /**
  100720. * Gets the perf counter used for animations time
  100721. */
  100722. get: function () {
  100723. return this._animationsTime;
  100724. },
  100725. enumerable: true,
  100726. configurable: true
  100727. });
  100728. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  100729. /**
  100730. * Gets the animations time capture status
  100731. */
  100732. get: function () {
  100733. return this._captureAnimationsTime;
  100734. },
  100735. /**
  100736. * Enable or disable the animations time capture
  100737. */
  100738. set: function (value) {
  100739. var _this = this;
  100740. if (value === this._captureAnimationsTime) {
  100741. return;
  100742. }
  100743. this._captureAnimationsTime = value;
  100744. if (value) {
  100745. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  100746. _this._animationsTime.endMonitoring();
  100747. });
  100748. }
  100749. else {
  100750. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  100751. this._onAfterAnimationsObserver = null;
  100752. }
  100753. },
  100754. enumerable: true,
  100755. configurable: true
  100756. });
  100757. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  100758. /**
  100759. * Gets the perf counter used for frame time capture
  100760. */
  100761. get: function () {
  100762. return this._frameTime;
  100763. },
  100764. enumerable: true,
  100765. configurable: true
  100766. });
  100767. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  100768. /**
  100769. * Gets the frame time capture status
  100770. */
  100771. get: function () {
  100772. return this._captureFrameTime;
  100773. },
  100774. /**
  100775. * Enable or disable the frame time capture
  100776. */
  100777. set: function (value) {
  100778. this._captureFrameTime = value;
  100779. },
  100780. enumerable: true,
  100781. configurable: true
  100782. });
  100783. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  100784. /**
  100785. * Gets the perf counter used for inter-frames time capture
  100786. */
  100787. get: function () {
  100788. return this._interFrameTime;
  100789. },
  100790. enumerable: true,
  100791. configurable: true
  100792. });
  100793. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  100794. /**
  100795. * Gets the inter-frames time capture status
  100796. */
  100797. get: function () {
  100798. return this._captureInterFrameTime;
  100799. },
  100800. /**
  100801. * Enable or disable the inter-frames time capture
  100802. */
  100803. set: function (value) {
  100804. this._captureInterFrameTime = value;
  100805. },
  100806. enumerable: true,
  100807. configurable: true
  100808. });
  100809. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  100810. /**
  100811. * Gets the perf counter used for render time capture
  100812. */
  100813. get: function () {
  100814. return this._renderTime;
  100815. },
  100816. enumerable: true,
  100817. configurable: true
  100818. });
  100819. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  100820. /**
  100821. * Gets the render time capture status
  100822. */
  100823. get: function () {
  100824. return this._captureRenderTime;
  100825. },
  100826. /**
  100827. * Enable or disable the render time capture
  100828. */
  100829. set: function (value) {
  100830. var _this = this;
  100831. if (value === this._captureRenderTime) {
  100832. return;
  100833. }
  100834. this._captureRenderTime = value;
  100835. if (value) {
  100836. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  100837. _this._renderTime.beginMonitoring();
  100838. BABYLON.Tools.StartPerformanceCounter("Main render");
  100839. });
  100840. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  100841. _this._renderTime.endMonitoring(false);
  100842. BABYLON.Tools.EndPerformanceCounter("Main render");
  100843. });
  100844. }
  100845. else {
  100846. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100847. this._onBeforeDrawPhaseObserver = null;
  100848. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100849. this._onAfterDrawPhaseObserver = null;
  100850. }
  100851. },
  100852. enumerable: true,
  100853. configurable: true
  100854. });
  100855. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  100856. /**
  100857. * Gets the perf counter used for camera render time capture
  100858. */
  100859. get: function () {
  100860. return this._cameraRenderTime;
  100861. },
  100862. enumerable: true,
  100863. configurable: true
  100864. });
  100865. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  100866. /**
  100867. * Gets the camera render time capture status
  100868. */
  100869. get: function () {
  100870. return this._captureCameraRenderTime;
  100871. },
  100872. /**
  100873. * Enable or disable the camera render time capture
  100874. */
  100875. set: function (value) {
  100876. var _this = this;
  100877. if (value === this._captureCameraRenderTime) {
  100878. return;
  100879. }
  100880. this._captureCameraRenderTime = value;
  100881. if (value) {
  100882. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  100883. _this._cameraRenderTime.beginMonitoring();
  100884. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  100885. });
  100886. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  100887. _this._cameraRenderTime.endMonitoring(false);
  100888. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  100889. });
  100890. }
  100891. else {
  100892. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  100893. this._onBeforeCameraRenderObserver = null;
  100894. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  100895. this._onAfterCameraRenderObserver = null;
  100896. }
  100897. },
  100898. enumerable: true,
  100899. configurable: true
  100900. });
  100901. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  100902. /**
  100903. * Gets the perf counter used for draw calls
  100904. */
  100905. get: function () {
  100906. return this.scene.getEngine()._drawCalls;
  100907. },
  100908. enumerable: true,
  100909. configurable: true
  100910. });
  100911. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  100912. /**
  100913. * Gets the perf counter used for texture collisions
  100914. */
  100915. get: function () {
  100916. return this.scene.getEngine()._textureCollisions;
  100917. },
  100918. enumerable: true,
  100919. configurable: true
  100920. });
  100921. SceneInstrumentation.prototype.dispose = function () {
  100922. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100923. this._onAfterRenderObserver = null;
  100924. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100925. this._onBeforeActiveMeshesEvaluationObserver = null;
  100926. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100927. this._onAfterActiveMeshesEvaluationObserver = null;
  100928. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100929. this._onBeforeRenderTargetsRenderObserver = null;
  100930. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100931. this._onAfterRenderTargetsRenderObserver = null;
  100932. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  100933. this._onBeforeAnimationsObserver = null;
  100934. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100935. this._onBeforeParticlesRenderingObserver = null;
  100936. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100937. this._onAfterParticlesRenderingObserver = null;
  100938. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  100939. this._onBeforeSpritesRenderingObserver = null;
  100940. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  100941. this._onAfterSpritesRenderingObserver = null;
  100942. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100943. this._onBeforeDrawPhaseObserver = null;
  100944. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100945. this._onAfterDrawPhaseObserver = null;
  100946. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  100947. this._onBeforePhysicsObserver = null;
  100948. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  100949. this._onAfterPhysicsObserver = null;
  100950. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  100951. this._onAfterAnimationsObserver = null;
  100952. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  100953. this._onBeforeCameraRenderObserver = null;
  100954. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  100955. this._onAfterCameraRenderObserver = null;
  100956. this.scene = null;
  100957. };
  100958. return SceneInstrumentation;
  100959. }());
  100960. BABYLON.SceneInstrumentation = SceneInstrumentation;
  100961. })(BABYLON || (BABYLON = {}));
  100962. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  100963. var BABYLON;
  100964. (function (BABYLON) {
  100965. /**
  100966. * @hidden
  100967. **/
  100968. var _TimeToken = /** @class */ (function () {
  100969. function _TimeToken() {
  100970. this._timeElapsedQueryEnded = false;
  100971. }
  100972. return _TimeToken;
  100973. }());
  100974. BABYLON._TimeToken = _TimeToken;
  100975. })(BABYLON || (BABYLON = {}));
  100976. //# sourceMappingURL=babylon.timeToken.js.map
  100977. var BABYLON;
  100978. (function (BABYLON) {
  100979. /**
  100980. * Background material defines definition.
  100981. * @hidden Mainly internal Use
  100982. */
  100983. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  100984. __extends(BackgroundMaterialDefines, _super);
  100985. /**
  100986. * Constructor of the defines.
  100987. */
  100988. function BackgroundMaterialDefines() {
  100989. var _this = _super.call(this) || this;
  100990. /**
  100991. * True if the diffuse texture is in use.
  100992. */
  100993. _this.DIFFUSE = false;
  100994. /**
  100995. * The direct UV channel to use.
  100996. */
  100997. _this.DIFFUSEDIRECTUV = 0;
  100998. /**
  100999. * True if the diffuse texture is in gamma space.
  101000. */
  101001. _this.GAMMADIFFUSE = false;
  101002. /**
  101003. * True if the diffuse texture has opacity in the alpha channel.
  101004. */
  101005. _this.DIFFUSEHASALPHA = false;
  101006. /**
  101007. * True if you want the material to fade to transparent at grazing angle.
  101008. */
  101009. _this.OPACITYFRESNEL = false;
  101010. /**
  101011. * True if an extra blur needs to be added in the reflection.
  101012. */
  101013. _this.REFLECTIONBLUR = false;
  101014. /**
  101015. * True if you want the material to fade to reflection at grazing angle.
  101016. */
  101017. _this.REFLECTIONFRESNEL = false;
  101018. /**
  101019. * True if you want the material to falloff as far as you move away from the scene center.
  101020. */
  101021. _this.REFLECTIONFALLOFF = false;
  101022. /**
  101023. * False if the current Webgl implementation does not support the texture lod extension.
  101024. */
  101025. _this.TEXTURELODSUPPORT = false;
  101026. /**
  101027. * True to ensure the data are premultiplied.
  101028. */
  101029. _this.PREMULTIPLYALPHA = false;
  101030. /**
  101031. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  101032. */
  101033. _this.USERGBCOLOR = false;
  101034. /**
  101035. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  101036. * stays aligned with the desired configuration.
  101037. */
  101038. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  101039. /**
  101040. * True to add noise in order to reduce the banding effect.
  101041. */
  101042. _this.NOISE = false;
  101043. /**
  101044. * is the reflection texture in BGR color scheme?
  101045. * Mainly used to solve a bug in ios10 video tag
  101046. */
  101047. _this.REFLECTIONBGR = false;
  101048. _this.IMAGEPROCESSING = false;
  101049. _this.VIGNETTE = false;
  101050. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  101051. _this.VIGNETTEBLENDMODEOPAQUE = false;
  101052. _this.TONEMAPPING = false;
  101053. _this.CONTRAST = false;
  101054. _this.COLORCURVES = false;
  101055. _this.COLORGRADING = false;
  101056. _this.COLORGRADING3D = false;
  101057. _this.SAMPLER3DGREENDEPTH = false;
  101058. _this.SAMPLER3DBGRMAP = false;
  101059. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  101060. _this.EXPOSURE = false;
  101061. // Reflection.
  101062. _this.REFLECTION = false;
  101063. _this.REFLECTIONMAP_3D = false;
  101064. _this.REFLECTIONMAP_SPHERICAL = false;
  101065. _this.REFLECTIONMAP_PLANAR = false;
  101066. _this.REFLECTIONMAP_CUBIC = false;
  101067. _this.REFLECTIONMAP_PROJECTION = false;
  101068. _this.REFLECTIONMAP_SKYBOX = false;
  101069. _this.REFLECTIONMAP_EXPLICIT = false;
  101070. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101071. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101072. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101073. _this.INVERTCUBICMAP = false;
  101074. _this.REFLECTIONMAP_OPPOSITEZ = false;
  101075. _this.LODINREFLECTIONALPHA = false;
  101076. _this.GAMMAREFLECTION = false;
  101077. _this.RGBDREFLECTION = false;
  101078. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  101079. // Default BJS.
  101080. _this.MAINUV1 = false;
  101081. _this.MAINUV2 = false;
  101082. _this.UV1 = false;
  101083. _this.UV2 = false;
  101084. _this.CLIPPLANE = false;
  101085. _this.POINTSIZE = false;
  101086. _this.FOG = false;
  101087. _this.NORMAL = false;
  101088. _this.NUM_BONE_INFLUENCERS = 0;
  101089. _this.BonesPerMesh = 0;
  101090. _this.INSTANCES = false;
  101091. _this.SHADOWFLOAT = false;
  101092. _this.rebuild();
  101093. return _this;
  101094. }
  101095. return BackgroundMaterialDefines;
  101096. }(BABYLON.MaterialDefines));
  101097. /**
  101098. * Background material used to create an efficient environement around your scene.
  101099. */
  101100. var BackgroundMaterial = /** @class */ (function (_super) {
  101101. __extends(BackgroundMaterial, _super);
  101102. /**
  101103. * Instantiates a Background Material in the given scene
  101104. * @param name The friendly name of the material
  101105. * @param scene The scene to add the material to
  101106. */
  101107. function BackgroundMaterial(name, scene) {
  101108. var _this = _super.call(this, name, scene) || this;
  101109. /**
  101110. * Key light Color (multiply against the environement texture)
  101111. */
  101112. _this.primaryColor = BABYLON.Color3.White();
  101113. _this._primaryColorShadowLevel = 0;
  101114. _this._primaryColorHighlightLevel = 0;
  101115. /**
  101116. * Reflection Texture used in the material.
  101117. * Should be author in a specific way for the best result (refer to the documentation).
  101118. */
  101119. _this.reflectionTexture = null;
  101120. /**
  101121. * Reflection Texture level of blur.
  101122. *
  101123. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  101124. * texture twice.
  101125. */
  101126. _this.reflectionBlur = 0;
  101127. /**
  101128. * Diffuse Texture used in the material.
  101129. * Should be author in a specific way for the best result (refer to the documentation).
  101130. */
  101131. _this.diffuseTexture = null;
  101132. _this._shadowLights = null;
  101133. /**
  101134. * Specify the list of lights casting shadow on the material.
  101135. * All scene shadow lights will be included if null.
  101136. */
  101137. _this.shadowLights = null;
  101138. /**
  101139. * Helps adjusting the shadow to a softer level if required.
  101140. * 0 means black shadows and 1 means no shadows.
  101141. */
  101142. _this.shadowLevel = 0;
  101143. /**
  101144. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  101145. * It is usually zero but might be interesting to modify according to your setup.
  101146. */
  101147. _this.sceneCenter = BABYLON.Vector3.Zero();
  101148. /**
  101149. * This helps specifying that the material is falling off to the sky box at grazing angle.
  101150. * This helps ensuring a nice transition when the camera goes under the ground.
  101151. */
  101152. _this.opacityFresnel = true;
  101153. /**
  101154. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  101155. * This helps adding a mirror texture on the ground.
  101156. */
  101157. _this.reflectionFresnel = false;
  101158. /**
  101159. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  101160. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  101161. */
  101162. _this.reflectionFalloffDistance = 0.0;
  101163. /**
  101164. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  101165. */
  101166. _this.reflectionAmount = 1.0;
  101167. /**
  101168. * This specifies the weight of the reflection at grazing angle.
  101169. */
  101170. _this.reflectionReflectance0 = 0.05;
  101171. /**
  101172. * This specifies the weight of the reflection at a perpendicular point of view.
  101173. */
  101174. _this.reflectionReflectance90 = 0.5;
  101175. /**
  101176. * Helps to directly use the maps channels instead of their level.
  101177. */
  101178. _this.useRGBColor = true;
  101179. /**
  101180. * This helps reducing the banding effect that could occur on the background.
  101181. */
  101182. _this.enableNoise = false;
  101183. _this._fovMultiplier = 1.0;
  101184. /**
  101185. * Enable the FOV adjustment feature controlled by fovMultiplier.
  101186. */
  101187. _this.useEquirectangularFOV = false;
  101188. _this._maxSimultaneousLights = 4;
  101189. /**
  101190. * Number of Simultaneous lights allowed on the material.
  101191. */
  101192. _this.maxSimultaneousLights = 4;
  101193. /**
  101194. * Keep track of the image processing observer to allow dispose and replace.
  101195. */
  101196. _this._imageProcessingObserver = null;
  101197. /**
  101198. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  101199. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  101200. */
  101201. _this.switchToBGR = false;
  101202. // Temp values kept as cache in the material.
  101203. _this._renderTargets = new BABYLON.SmartArray(16);
  101204. _this._reflectionControls = BABYLON.Vector4.Zero();
  101205. _this._white = BABYLON.Color3.White();
  101206. _this._primaryShadowColor = BABYLON.Color3.Black();
  101207. _this._primaryHighlightColor = BABYLON.Color3.Black();
  101208. // Setup the default processing configuration to the scene.
  101209. _this._attachImageProcessingConfiguration(null);
  101210. _this.getRenderTargetTextures = function () {
  101211. _this._renderTargets.reset();
  101212. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  101213. _this._renderTargets.push(_this._diffuseTexture);
  101214. }
  101215. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  101216. _this._renderTargets.push(_this._reflectionTexture);
  101217. }
  101218. return _this._renderTargets;
  101219. };
  101220. return _this;
  101221. }
  101222. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  101223. /**
  101224. * Experimental Internal Use Only.
  101225. *
  101226. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  101227. * This acts as a helper to set the primary color to a more "human friendly" value.
  101228. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  101229. * output color as close as possible from the chosen value.
  101230. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  101231. * part of lighting setup.)
  101232. */
  101233. get: function () {
  101234. return this.__perceptualColor;
  101235. },
  101236. set: function (value) {
  101237. this.__perceptualColor = value;
  101238. this._computePrimaryColorFromPerceptualColor();
  101239. this._markAllSubMeshesAsLightsDirty();
  101240. },
  101241. enumerable: true,
  101242. configurable: true
  101243. });
  101244. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  101245. /**
  101246. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  101247. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  101248. */
  101249. get: function () {
  101250. return this._primaryColorShadowLevel;
  101251. },
  101252. set: function (value) {
  101253. this._primaryColorShadowLevel = value;
  101254. this._computePrimaryColors();
  101255. this._markAllSubMeshesAsLightsDirty();
  101256. },
  101257. enumerable: true,
  101258. configurable: true
  101259. });
  101260. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  101261. /**
  101262. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  101263. * The primary color is used at the level chosen to define what the white area would look.
  101264. */
  101265. get: function () {
  101266. return this._primaryColorHighlightLevel;
  101267. },
  101268. set: function (value) {
  101269. this._primaryColorHighlightLevel = value;
  101270. this._computePrimaryColors();
  101271. this._markAllSubMeshesAsLightsDirty();
  101272. },
  101273. enumerable: true,
  101274. configurable: true
  101275. });
  101276. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  101277. /**
  101278. * Sets the reflection reflectance fresnel values according to the default standard
  101279. * empirically know to work well :-)
  101280. */
  101281. set: function (value) {
  101282. var reflectionWeight = value;
  101283. if (reflectionWeight < 0.5) {
  101284. reflectionWeight = reflectionWeight * 2.0;
  101285. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  101286. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  101287. }
  101288. else {
  101289. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  101290. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  101291. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  101292. }
  101293. },
  101294. enumerable: true,
  101295. configurable: true
  101296. });
  101297. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  101298. /**
  101299. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101300. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  101301. * Recommended to be keep at 1.0 except for special cases.
  101302. */
  101303. get: function () {
  101304. return this._fovMultiplier;
  101305. },
  101306. set: function (value) {
  101307. if (isNaN(value)) {
  101308. value = 1.0;
  101309. }
  101310. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  101311. },
  101312. enumerable: true,
  101313. configurable: true
  101314. });
  101315. /**
  101316. * Attaches a new image processing configuration to the PBR Material.
  101317. * @param configuration (if null the scene configuration will be use)
  101318. */
  101319. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  101320. var _this = this;
  101321. if (configuration === this._imageProcessingConfiguration) {
  101322. return;
  101323. }
  101324. // Detaches observer.
  101325. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101326. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101327. }
  101328. // Pick the scene configuration if needed.
  101329. if (!configuration) {
  101330. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  101331. }
  101332. else {
  101333. this._imageProcessingConfiguration = configuration;
  101334. }
  101335. // Attaches observer.
  101336. if (this._imageProcessingConfiguration) {
  101337. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  101338. _this._computePrimaryColorFromPerceptualColor();
  101339. _this._markAllSubMeshesAsImageProcessingDirty();
  101340. });
  101341. }
  101342. };
  101343. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  101344. /**
  101345. * Gets the image processing configuration used either in this material.
  101346. */
  101347. get: function () {
  101348. return this._imageProcessingConfiguration;
  101349. },
  101350. /**
  101351. * Sets the Default image processing configuration used either in the this material.
  101352. *
  101353. * If sets to null, the scene one is in use.
  101354. */
  101355. set: function (value) {
  101356. this._attachImageProcessingConfiguration(value);
  101357. // Ensure the effect will be rebuilt.
  101358. this._markAllSubMeshesAsTexturesDirty();
  101359. },
  101360. enumerable: true,
  101361. configurable: true
  101362. });
  101363. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  101364. /**
  101365. * Gets wether the color curves effect is enabled.
  101366. */
  101367. get: function () {
  101368. return this.imageProcessingConfiguration.colorCurvesEnabled;
  101369. },
  101370. /**
  101371. * Sets wether the color curves effect is enabled.
  101372. */
  101373. set: function (value) {
  101374. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  101375. },
  101376. enumerable: true,
  101377. configurable: true
  101378. });
  101379. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  101380. /**
  101381. * Gets wether the color grading effect is enabled.
  101382. */
  101383. get: function () {
  101384. return this.imageProcessingConfiguration.colorGradingEnabled;
  101385. },
  101386. /**
  101387. * Gets wether the color grading effect is enabled.
  101388. */
  101389. set: function (value) {
  101390. this.imageProcessingConfiguration.colorGradingEnabled = value;
  101391. },
  101392. enumerable: true,
  101393. configurable: true
  101394. });
  101395. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  101396. /**
  101397. * Gets wether tonemapping is enabled or not.
  101398. */
  101399. get: function () {
  101400. return this._imageProcessingConfiguration.toneMappingEnabled;
  101401. },
  101402. /**
  101403. * Sets wether tonemapping is enabled or not
  101404. */
  101405. set: function (value) {
  101406. this._imageProcessingConfiguration.toneMappingEnabled = value;
  101407. },
  101408. enumerable: true,
  101409. configurable: true
  101410. });
  101411. ;
  101412. ;
  101413. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  101414. /**
  101415. * The camera exposure used on this material.
  101416. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101417. * This corresponds to a photographic exposure.
  101418. */
  101419. get: function () {
  101420. return this._imageProcessingConfiguration.exposure;
  101421. },
  101422. /**
  101423. * The camera exposure used on this material.
  101424. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101425. * This corresponds to a photographic exposure.
  101426. */
  101427. set: function (value) {
  101428. this._imageProcessingConfiguration.exposure = value;
  101429. },
  101430. enumerable: true,
  101431. configurable: true
  101432. });
  101433. ;
  101434. ;
  101435. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  101436. /**
  101437. * Gets The camera contrast used on this material.
  101438. */
  101439. get: function () {
  101440. return this._imageProcessingConfiguration.contrast;
  101441. },
  101442. /**
  101443. * Sets The camera contrast used on this material.
  101444. */
  101445. set: function (value) {
  101446. this._imageProcessingConfiguration.contrast = value;
  101447. },
  101448. enumerable: true,
  101449. configurable: true
  101450. });
  101451. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  101452. /**
  101453. * Gets the Color Grading 2D Lookup Texture.
  101454. */
  101455. get: function () {
  101456. return this._imageProcessingConfiguration.colorGradingTexture;
  101457. },
  101458. /**
  101459. * Sets the Color Grading 2D Lookup Texture.
  101460. */
  101461. set: function (value) {
  101462. this.imageProcessingConfiguration.colorGradingTexture = value;
  101463. },
  101464. enumerable: true,
  101465. configurable: true
  101466. });
  101467. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  101468. /**
  101469. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101470. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101471. * 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;
  101472. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101473. */
  101474. get: function () {
  101475. return this.imageProcessingConfiguration.colorCurves;
  101476. },
  101477. /**
  101478. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101479. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101480. * 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;
  101481. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101482. */
  101483. set: function (value) {
  101484. this.imageProcessingConfiguration.colorCurves = value;
  101485. },
  101486. enumerable: true,
  101487. configurable: true
  101488. });
  101489. /**
  101490. * The entire material has been created in order to prevent overdraw.
  101491. * @returns false
  101492. */
  101493. BackgroundMaterial.prototype.needAlphaTesting = function () {
  101494. return true;
  101495. };
  101496. /**
  101497. * The entire material has been created in order to prevent overdraw.
  101498. * @returns true if blending is enable
  101499. */
  101500. BackgroundMaterial.prototype.needAlphaBlending = function () {
  101501. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  101502. };
  101503. /**
  101504. * Checks wether the material is ready to be rendered for a given mesh.
  101505. * @param mesh The mesh to render
  101506. * @param subMesh The submesh to check against
  101507. * @param useInstances Specify wether or not the material is used with instances
  101508. * @returns true if all the dependencies are ready (Textures, Effects...)
  101509. */
  101510. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  101511. var _this = this;
  101512. if (useInstances === void 0) { useInstances = false; }
  101513. if (subMesh.effect && this.isFrozen) {
  101514. if (this._wasPreviouslyReady) {
  101515. return true;
  101516. }
  101517. }
  101518. if (!subMesh._materialDefines) {
  101519. subMesh._materialDefines = new BackgroundMaterialDefines();
  101520. }
  101521. var scene = this.getScene();
  101522. var defines = subMesh._materialDefines;
  101523. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  101524. if (defines._renderId === scene.getRenderId()) {
  101525. return true;
  101526. }
  101527. }
  101528. var engine = scene.getEngine();
  101529. // Lights
  101530. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  101531. defines._needNormals = true;
  101532. // Textures
  101533. if (defines._areTexturesDirty) {
  101534. defines._needUVs = false;
  101535. if (scene.texturesEnabled) {
  101536. if (scene.getEngine().getCaps().textureLOD) {
  101537. defines.TEXTURELODSUPPORT = true;
  101538. }
  101539. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101540. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  101541. return false;
  101542. }
  101543. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  101544. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  101545. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  101546. defines.OPACITYFRESNEL = this._opacityFresnel;
  101547. }
  101548. else {
  101549. defines.DIFFUSE = false;
  101550. defines.DIFFUSEHASALPHA = false;
  101551. defines.GAMMADIFFUSE = false;
  101552. defines.OPACITYFRESNEL = false;
  101553. }
  101554. var reflectionTexture = this._reflectionTexture;
  101555. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101556. if (!reflectionTexture.isReadyOrNotBlocking()) {
  101557. return false;
  101558. }
  101559. defines.REFLECTION = true;
  101560. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  101561. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  101562. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  101563. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  101564. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  101565. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  101566. defines.REFLECTIONBGR = this.switchToBGR;
  101567. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  101568. defines.INVERTCUBICMAP = true;
  101569. }
  101570. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  101571. switch (reflectionTexture.coordinatesMode) {
  101572. case BABYLON.Texture.EXPLICIT_MODE:
  101573. defines.REFLECTIONMAP_EXPLICIT = true;
  101574. break;
  101575. case BABYLON.Texture.PLANAR_MODE:
  101576. defines.REFLECTIONMAP_PLANAR = true;
  101577. break;
  101578. case BABYLON.Texture.PROJECTION_MODE:
  101579. defines.REFLECTIONMAP_PROJECTION = true;
  101580. break;
  101581. case BABYLON.Texture.SKYBOX_MODE:
  101582. defines.REFLECTIONMAP_SKYBOX = true;
  101583. break;
  101584. case BABYLON.Texture.SPHERICAL_MODE:
  101585. defines.REFLECTIONMAP_SPHERICAL = true;
  101586. break;
  101587. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  101588. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  101589. break;
  101590. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  101591. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  101592. break;
  101593. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  101594. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  101595. break;
  101596. case BABYLON.Texture.CUBIC_MODE:
  101597. case BABYLON.Texture.INVCUBIC_MODE:
  101598. default:
  101599. defines.REFLECTIONMAP_CUBIC = true;
  101600. break;
  101601. }
  101602. if (this.reflectionFresnel) {
  101603. defines.REFLECTIONFRESNEL = true;
  101604. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  101605. this._reflectionControls.x = this.reflectionAmount;
  101606. this._reflectionControls.y = this.reflectionReflectance0;
  101607. this._reflectionControls.z = this.reflectionReflectance90;
  101608. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  101609. }
  101610. else {
  101611. defines.REFLECTIONFRESNEL = false;
  101612. defines.REFLECTIONFALLOFF = false;
  101613. }
  101614. }
  101615. else {
  101616. defines.REFLECTION = false;
  101617. defines.REFLECTIONFRESNEL = false;
  101618. defines.REFLECTIONFALLOFF = false;
  101619. defines.REFLECTIONBLUR = false;
  101620. defines.REFLECTIONMAP_3D = false;
  101621. defines.REFLECTIONMAP_SPHERICAL = false;
  101622. defines.REFLECTIONMAP_PLANAR = false;
  101623. defines.REFLECTIONMAP_CUBIC = false;
  101624. defines.REFLECTIONMAP_PROJECTION = false;
  101625. defines.REFLECTIONMAP_SKYBOX = false;
  101626. defines.REFLECTIONMAP_EXPLICIT = false;
  101627. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101628. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101629. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101630. defines.INVERTCUBICMAP = false;
  101631. defines.REFLECTIONMAP_OPPOSITEZ = false;
  101632. defines.LODINREFLECTIONALPHA = false;
  101633. defines.GAMMAREFLECTION = false;
  101634. defines.RGBDREFLECTION = false;
  101635. }
  101636. }
  101637. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  101638. defines.USERGBCOLOR = this._useRGBColor;
  101639. defines.NOISE = this._enableNoise;
  101640. }
  101641. if (defines._areLightsDirty) {
  101642. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  101643. }
  101644. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  101645. if (!this._imageProcessingConfiguration.isReady()) {
  101646. return false;
  101647. }
  101648. this._imageProcessingConfiguration.prepareDefines(defines);
  101649. }
  101650. // Misc.
  101651. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  101652. // Values that need to be evaluated on every frame
  101653. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  101654. // Attribs
  101655. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  101656. if (mesh) {
  101657. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  101658. mesh.createNormals(true);
  101659. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  101660. }
  101661. }
  101662. }
  101663. // Get correct effect
  101664. if (defines.isDirty) {
  101665. defines.markAsProcessed();
  101666. scene.resetCachedMaterial();
  101667. // Fallbacks
  101668. var fallbacks = new BABYLON.EffectFallbacks();
  101669. if (defines.FOG) {
  101670. fallbacks.addFallback(0, "FOG");
  101671. }
  101672. if (defines.POINTSIZE) {
  101673. fallbacks.addFallback(1, "POINTSIZE");
  101674. }
  101675. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  101676. if (defines.NUM_BONE_INFLUENCERS > 0) {
  101677. fallbacks.addCPUSkinningFallback(0, mesh);
  101678. }
  101679. //Attributes
  101680. var attribs = [BABYLON.VertexBuffer.PositionKind];
  101681. if (defines.NORMAL) {
  101682. attribs.push(BABYLON.VertexBuffer.NormalKind);
  101683. }
  101684. if (defines.UV1) {
  101685. attribs.push(BABYLON.VertexBuffer.UVKind);
  101686. }
  101687. if (defines.UV2) {
  101688. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101689. }
  101690. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  101691. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  101692. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  101693. "vFogInfos", "vFogColor", "pointSize",
  101694. "vClipPlane", "mBones",
  101695. "vPrimaryColor", "vPrimaryColorShadow",
  101696. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  101697. "shadowLevel", "alpha",
  101698. "vBackgroundCenter", "vReflectionControl",
  101699. "vDiffuseInfos", "diffuseMatrix",
  101700. ];
  101701. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  101702. var uniformBuffers = ["Material", "Scene"];
  101703. if (BABYLON.ImageProcessingConfiguration) {
  101704. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  101705. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  101706. }
  101707. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  101708. uniformsNames: uniforms,
  101709. uniformBuffersNames: uniformBuffers,
  101710. samplers: samplers,
  101711. defines: defines,
  101712. maxSimultaneousLights: this._maxSimultaneousLights
  101713. });
  101714. var onCompiled = function (effect) {
  101715. if (_this.onCompiled) {
  101716. _this.onCompiled(effect);
  101717. }
  101718. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  101719. };
  101720. var join = defines.toString();
  101721. subMesh.setEffect(scene.getEngine().createEffect("background", {
  101722. attributes: attribs,
  101723. uniformsNames: uniforms,
  101724. uniformBuffersNames: uniformBuffers,
  101725. samplers: samplers,
  101726. defines: join,
  101727. fallbacks: fallbacks,
  101728. onCompiled: onCompiled,
  101729. onError: this.onError,
  101730. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  101731. }, engine), defines);
  101732. this.buildUniformLayout();
  101733. }
  101734. if (!subMesh.effect || !subMesh.effect.isReady()) {
  101735. return false;
  101736. }
  101737. defines._renderId = scene.getRenderId();
  101738. this._wasPreviouslyReady = true;
  101739. return true;
  101740. };
  101741. /**
  101742. * Compute the primary color according to the chosen perceptual color.
  101743. */
  101744. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  101745. if (!this.__perceptualColor) {
  101746. return;
  101747. }
  101748. this._primaryColor.copyFrom(this.__perceptualColor);
  101749. // Revert gamma space.
  101750. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  101751. // Revert image processing configuration.
  101752. if (this._imageProcessingConfiguration) {
  101753. // Revert Exposure.
  101754. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  101755. }
  101756. this._computePrimaryColors();
  101757. };
  101758. /**
  101759. * Compute the highlights and shadow colors according to their chosen levels.
  101760. */
  101761. BackgroundMaterial.prototype._computePrimaryColors = function () {
  101762. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  101763. return;
  101764. }
  101765. // Find the highlight color based on the configuration.
  101766. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  101767. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  101768. // Find the shadow color based on the configuration.
  101769. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  101770. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  101771. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  101772. };
  101773. /**
  101774. * Build the uniform buffer used in the material.
  101775. */
  101776. BackgroundMaterial.prototype.buildUniformLayout = function () {
  101777. // Order is important !
  101778. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  101779. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  101780. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  101781. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  101782. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  101783. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  101784. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  101785. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  101786. this._uniformBuffer.addUniform("pointSize", 1);
  101787. this._uniformBuffer.addUniform("shadowLevel", 1);
  101788. this._uniformBuffer.addUniform("alpha", 1);
  101789. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  101790. this._uniformBuffer.addUniform("vReflectionControl", 4);
  101791. this._uniformBuffer.create();
  101792. };
  101793. /**
  101794. * Unbind the material.
  101795. */
  101796. BackgroundMaterial.prototype.unbind = function () {
  101797. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  101798. this._uniformBuffer.setTexture("diffuseSampler", null);
  101799. }
  101800. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  101801. this._uniformBuffer.setTexture("reflectionSampler", null);
  101802. }
  101803. _super.prototype.unbind.call(this);
  101804. };
  101805. /**
  101806. * Bind only the world matrix to the material.
  101807. * @param world The world matrix to bind.
  101808. */
  101809. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  101810. this._activeEffect.setMatrix("world", world);
  101811. };
  101812. /**
  101813. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  101814. * @param world The world matrix to bind.
  101815. * @param subMesh The submesh to bind for.
  101816. */
  101817. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  101818. var scene = this.getScene();
  101819. var defines = subMesh._materialDefines;
  101820. if (!defines) {
  101821. return;
  101822. }
  101823. var effect = subMesh.effect;
  101824. if (!effect) {
  101825. return;
  101826. }
  101827. this._activeEffect = effect;
  101828. // Matrices
  101829. this.bindOnlyWorldMatrix(world);
  101830. // Bones
  101831. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  101832. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  101833. if (mustRebind) {
  101834. this._uniformBuffer.bindToEffect(effect, "Material");
  101835. this.bindViewProjection(effect);
  101836. var reflectionTexture = this._reflectionTexture;
  101837. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  101838. // Texture uniforms
  101839. if (scene.texturesEnabled) {
  101840. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101841. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  101842. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  101843. }
  101844. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101845. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  101846. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  101847. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  101848. }
  101849. }
  101850. if (this.shadowLevel > 0) {
  101851. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  101852. }
  101853. this._uniformBuffer.updateFloat("alpha", this.alpha);
  101854. // Point size
  101855. if (this.pointsCloud) {
  101856. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  101857. }
  101858. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  101859. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  101860. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  101861. }
  101862. else {
  101863. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  101864. }
  101865. }
  101866. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  101867. // Textures
  101868. if (scene.texturesEnabled) {
  101869. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101870. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  101871. }
  101872. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101873. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  101874. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101875. }
  101876. else if (!defines.REFLECTIONBLUR) {
  101877. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101878. }
  101879. else {
  101880. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  101881. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  101882. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  101883. }
  101884. if (defines.REFLECTIONFRESNEL) {
  101885. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  101886. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  101887. }
  101888. }
  101889. }
  101890. // Clip plane
  101891. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  101892. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  101893. }
  101894. if (mustRebind || !this.isFrozen) {
  101895. if (scene.lightsEnabled) {
  101896. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  101897. }
  101898. // View
  101899. this.bindView(effect);
  101900. // Fog
  101901. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  101902. // image processing
  101903. if (this._imageProcessingConfiguration) {
  101904. this._imageProcessingConfiguration.bind(this._activeEffect);
  101905. }
  101906. }
  101907. this._uniformBuffer.update();
  101908. this._afterBind(mesh, this._activeEffect);
  101909. };
  101910. /**
  101911. * Dispose the material.
  101912. * @param forceDisposeEffect Force disposal of the associated effect.
  101913. * @param forceDisposeTextures Force disposal of the associated textures.
  101914. */
  101915. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  101916. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  101917. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  101918. if (forceDisposeTextures) {
  101919. if (this.diffuseTexture) {
  101920. this.diffuseTexture.dispose();
  101921. }
  101922. if (this.reflectionTexture) {
  101923. this.reflectionTexture.dispose();
  101924. }
  101925. }
  101926. this._renderTargets.dispose();
  101927. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101928. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101929. }
  101930. _super.prototype.dispose.call(this, forceDisposeEffect);
  101931. };
  101932. /**
  101933. * Clones the material.
  101934. * @param name The cloned name.
  101935. * @returns The cloned material.
  101936. */
  101937. BackgroundMaterial.prototype.clone = function (name) {
  101938. var _this = this;
  101939. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  101940. };
  101941. /**
  101942. * Serializes the current material to its JSON representation.
  101943. * @returns The JSON representation.
  101944. */
  101945. BackgroundMaterial.prototype.serialize = function () {
  101946. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101947. serializationObject.customType = "BABYLON.BackgroundMaterial";
  101948. return serializationObject;
  101949. };
  101950. /**
  101951. * Gets the class name of the material
  101952. * @returns "BackgroundMaterial"
  101953. */
  101954. BackgroundMaterial.prototype.getClassName = function () {
  101955. return "BackgroundMaterial";
  101956. };
  101957. /**
  101958. * Parse a JSON input to create back a background material.
  101959. * @param source The JSON data to parse
  101960. * @param scene The scene to create the parsed material in
  101961. * @param rootUrl The root url of the assets the material depends upon
  101962. * @returns the instantiated BackgroundMaterial.
  101963. */
  101964. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  101965. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  101966. };
  101967. /**
  101968. * Standard reflectance value at parallel view angle.
  101969. */
  101970. BackgroundMaterial.StandardReflectance0 = 0.05;
  101971. /**
  101972. * Standard reflectance value at grazing angle.
  101973. */
  101974. BackgroundMaterial.StandardReflectance90 = 0.5;
  101975. __decorate([
  101976. BABYLON.serializeAsColor3()
  101977. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  101978. __decorate([
  101979. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  101980. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  101981. __decorate([
  101982. BABYLON.serializeAsColor3()
  101983. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  101984. __decorate([
  101985. BABYLON.serialize()
  101986. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  101987. __decorate([
  101988. BABYLON.serialize()
  101989. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  101990. __decorate([
  101991. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  101992. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  101993. __decorate([
  101994. BABYLON.serializeAsTexture()
  101995. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  101996. __decorate([
  101997. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101998. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  101999. __decorate([
  102000. BABYLON.serialize()
  102001. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  102002. __decorate([
  102003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102004. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  102005. __decorate([
  102006. BABYLON.serializeAsTexture()
  102007. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  102008. __decorate([
  102009. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102010. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  102011. __decorate([
  102012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102013. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  102014. __decorate([
  102015. BABYLON.serialize()
  102016. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  102017. __decorate([
  102018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102019. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  102020. __decorate([
  102021. BABYLON.serializeAsVector3()
  102022. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  102023. __decorate([
  102024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102025. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  102026. __decorate([
  102027. BABYLON.serialize()
  102028. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  102029. __decorate([
  102030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102031. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  102032. __decorate([
  102033. BABYLON.serialize()
  102034. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  102035. __decorate([
  102036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102037. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  102038. __decorate([
  102039. BABYLON.serialize()
  102040. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  102041. __decorate([
  102042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102043. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  102044. __decorate([
  102045. BABYLON.serialize()
  102046. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  102047. __decorate([
  102048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102049. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  102050. __decorate([
  102051. BABYLON.serialize()
  102052. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  102053. __decorate([
  102054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102055. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  102056. __decorate([
  102057. BABYLON.serialize()
  102058. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  102059. __decorate([
  102060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102061. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  102062. __decorate([
  102063. BABYLON.serialize()
  102064. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  102065. __decorate([
  102066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102067. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  102068. __decorate([
  102069. BABYLON.serialize()
  102070. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  102071. __decorate([
  102072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102073. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  102074. __decorate([
  102075. BABYLON.serialize()
  102076. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  102077. __decorate([
  102078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  102079. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  102080. __decorate([
  102081. BABYLON.serializeAsImageProcessingConfiguration()
  102082. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  102083. return BackgroundMaterial;
  102084. }(BABYLON.PushMaterial));
  102085. BABYLON.BackgroundMaterial = BackgroundMaterial;
  102086. })(BABYLON || (BABYLON = {}));
  102087. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  102088. var __assign = (this && this.__assign) || Object.assign || function(t) {
  102089. for (var s, i = 1, n = arguments.length; i < n; i++) {
  102090. s = arguments[i];
  102091. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  102092. t[p] = s[p];
  102093. }
  102094. return t;
  102095. };
  102096. var BABYLON;
  102097. (function (BABYLON) {
  102098. /**
  102099. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  102100. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  102101. * It also helps with the default setup of your imageProcessing configuration.
  102102. */
  102103. var EnvironmentHelper = /** @class */ (function () {
  102104. /**
  102105. * constructor
  102106. * @param options
  102107. * @param scene The scene to add the material to
  102108. */
  102109. function EnvironmentHelper(options, scene) {
  102110. var _this = this;
  102111. this._errorHandler = function (message, exception) {
  102112. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  102113. };
  102114. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  102115. this._scene = scene;
  102116. this.onErrorObservable = new BABYLON.Observable();
  102117. this._setupBackground();
  102118. this._setupImageProcessing();
  102119. }
  102120. /**
  102121. * Creates the default options for the helper.
  102122. */
  102123. EnvironmentHelper._getDefaultOptions = function () {
  102124. return {
  102125. createGround: true,
  102126. groundSize: 15,
  102127. groundTexture: this._groundTextureCDNUrl,
  102128. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102129. groundOpacity: 0.9,
  102130. enableGroundShadow: true,
  102131. groundShadowLevel: 0.5,
  102132. enableGroundMirror: false,
  102133. groundMirrorSizeRatio: 0.3,
  102134. groundMirrorBlurKernel: 64,
  102135. groundMirrorAmount: 1,
  102136. groundMirrorFresnelWeight: 1,
  102137. groundMirrorFallOffDistance: 0,
  102138. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  102139. groundYBias: 0.00001,
  102140. createSkybox: true,
  102141. skyboxSize: 20,
  102142. skyboxTexture: this._skyboxTextureCDNUrl,
  102143. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  102144. backgroundYRotation: 0,
  102145. sizeAuto: true,
  102146. rootPosition: BABYLON.Vector3.Zero(),
  102147. setupImageProcessing: true,
  102148. environmentTexture: this._environmentTextureCDNUrl,
  102149. cameraExposure: 0.8,
  102150. cameraContrast: 1.2,
  102151. toneMappingEnabled: true,
  102152. };
  102153. };
  102154. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  102155. /**
  102156. * Gets the root mesh created by the helper.
  102157. */
  102158. get: function () {
  102159. return this._rootMesh;
  102160. },
  102161. enumerable: true,
  102162. configurable: true
  102163. });
  102164. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  102165. /**
  102166. * Gets the skybox created by the helper.
  102167. */
  102168. get: function () {
  102169. return this._skybox;
  102170. },
  102171. enumerable: true,
  102172. configurable: true
  102173. });
  102174. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  102175. /**
  102176. * Gets the skybox texture created by the helper.
  102177. */
  102178. get: function () {
  102179. return this._skyboxTexture;
  102180. },
  102181. enumerable: true,
  102182. configurable: true
  102183. });
  102184. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  102185. /**
  102186. * Gets the skybox material created by the helper.
  102187. */
  102188. get: function () {
  102189. return this._skyboxMaterial;
  102190. },
  102191. enumerable: true,
  102192. configurable: true
  102193. });
  102194. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  102195. /**
  102196. * Gets the ground mesh created by the helper.
  102197. */
  102198. get: function () {
  102199. return this._ground;
  102200. },
  102201. enumerable: true,
  102202. configurable: true
  102203. });
  102204. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  102205. /**
  102206. * Gets the ground texture created by the helper.
  102207. */
  102208. get: function () {
  102209. return this._groundTexture;
  102210. },
  102211. enumerable: true,
  102212. configurable: true
  102213. });
  102214. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  102215. /**
  102216. * Gets the ground mirror created by the helper.
  102217. */
  102218. get: function () {
  102219. return this._groundMirror;
  102220. },
  102221. enumerable: true,
  102222. configurable: true
  102223. });
  102224. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  102225. /**
  102226. * Gets the ground mirror render list to helps pushing the meshes
  102227. * you wish in the ground reflection.
  102228. */
  102229. get: function () {
  102230. if (this._groundMirror) {
  102231. return this._groundMirror.renderList;
  102232. }
  102233. return null;
  102234. },
  102235. enumerable: true,
  102236. configurable: true
  102237. });
  102238. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  102239. /**
  102240. * Gets the ground material created by the helper.
  102241. */
  102242. get: function () {
  102243. return this._groundMaterial;
  102244. },
  102245. enumerable: true,
  102246. configurable: true
  102247. });
  102248. /**
  102249. * Updates the background according to the new options
  102250. * @param options
  102251. */
  102252. EnvironmentHelper.prototype.updateOptions = function (options) {
  102253. var newOptions = __assign({}, this._options, options);
  102254. if (this._ground && !newOptions.createGround) {
  102255. this._ground.dispose();
  102256. this._ground = null;
  102257. }
  102258. if (this._groundMaterial && !newOptions.createGround) {
  102259. this._groundMaterial.dispose();
  102260. this._groundMaterial = null;
  102261. }
  102262. if (this._groundTexture) {
  102263. if (this._options.groundTexture != newOptions.groundTexture) {
  102264. this._groundTexture.dispose();
  102265. this._groundTexture = null;
  102266. }
  102267. }
  102268. if (this._skybox && !newOptions.createSkybox) {
  102269. this._skybox.dispose();
  102270. this._skybox = null;
  102271. }
  102272. if (this._skyboxMaterial && !newOptions.createSkybox) {
  102273. this._skyboxMaterial.dispose();
  102274. this._skyboxMaterial = null;
  102275. }
  102276. if (this._skyboxTexture) {
  102277. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  102278. this._skyboxTexture.dispose();
  102279. this._skyboxTexture = null;
  102280. }
  102281. }
  102282. if (this._groundMirror && !newOptions.enableGroundMirror) {
  102283. this._groundMirror.dispose();
  102284. this._groundMirror = null;
  102285. }
  102286. if (this._scene.environmentTexture) {
  102287. if (this._options.environmentTexture != newOptions.environmentTexture) {
  102288. this._scene.environmentTexture.dispose();
  102289. }
  102290. }
  102291. this._options = newOptions;
  102292. this._setupBackground();
  102293. this._setupImageProcessing();
  102294. };
  102295. /**
  102296. * Sets the primary color of all the available elements.
  102297. * @param color the main color to affect to the ground and the background
  102298. */
  102299. EnvironmentHelper.prototype.setMainColor = function (color) {
  102300. if (this.groundMaterial) {
  102301. this.groundMaterial.primaryColor = color;
  102302. }
  102303. if (this.skyboxMaterial) {
  102304. this.skyboxMaterial.primaryColor = color;
  102305. }
  102306. if (this.groundMirror) {
  102307. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  102308. }
  102309. };
  102310. /**
  102311. * Setup the image processing according to the specified options.
  102312. */
  102313. EnvironmentHelper.prototype._setupImageProcessing = function () {
  102314. if (this._options.setupImageProcessing) {
  102315. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  102316. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  102317. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  102318. this._setupEnvironmentTexture();
  102319. }
  102320. };
  102321. /**
  102322. * Setup the environment texture according to the specified options.
  102323. */
  102324. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  102325. if (this._scene.environmentTexture) {
  102326. return;
  102327. }
  102328. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  102329. this._scene.environmentTexture = this._options.environmentTexture;
  102330. return;
  102331. }
  102332. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  102333. this._scene.environmentTexture = environmentTexture;
  102334. };
  102335. /**
  102336. * Setup the background according to the specified options.
  102337. */
  102338. EnvironmentHelper.prototype._setupBackground = function () {
  102339. if (!this._rootMesh) {
  102340. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  102341. }
  102342. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  102343. var sceneSize = this._getSceneSize();
  102344. if (this._options.createGround) {
  102345. this._setupGround(sceneSize);
  102346. this._setupGroundMaterial();
  102347. this._setupGroundDiffuseTexture();
  102348. if (this._options.enableGroundMirror) {
  102349. this._setupGroundMirrorTexture(sceneSize);
  102350. }
  102351. this._setupMirrorInGroundMaterial();
  102352. }
  102353. if (this._options.createSkybox) {
  102354. this._setupSkybox(sceneSize);
  102355. this._setupSkyboxMaterial();
  102356. this._setupSkyboxReflectionTexture();
  102357. }
  102358. this._rootMesh.position.x = sceneSize.rootPosition.x;
  102359. this._rootMesh.position.z = sceneSize.rootPosition.z;
  102360. this._rootMesh.position.y = sceneSize.rootPosition.y;
  102361. };
  102362. /**
  102363. * Get the scene sizes according to the setup.
  102364. */
  102365. EnvironmentHelper.prototype._getSceneSize = function () {
  102366. var _this = this;
  102367. var groundSize = this._options.groundSize;
  102368. var skyboxSize = this._options.skyboxSize;
  102369. var rootPosition = this._options.rootPosition;
  102370. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  102371. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102372. }
  102373. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  102374. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  102375. });
  102376. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  102377. if (this._options.sizeAuto) {
  102378. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  102379. this._scene.activeCamera.upperRadiusLimit) {
  102380. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  102381. skyboxSize = groundSize;
  102382. }
  102383. var sceneDiagonalLenght = sceneDiagonal.length();
  102384. if (sceneDiagonalLenght > groundSize) {
  102385. groundSize = sceneDiagonalLenght * 2;
  102386. skyboxSize = groundSize;
  102387. }
  102388. // 10 % bigger.
  102389. groundSize *= 1.1;
  102390. skyboxSize *= 1.5;
  102391. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  102392. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  102393. }
  102394. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  102395. };
  102396. /**
  102397. * Setup the ground according to the specified options.
  102398. */
  102399. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  102400. var _this = this;
  102401. if (!this._ground || this._ground.isDisposed()) {
  102402. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  102403. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  102404. this._ground.parent = this._rootMesh;
  102405. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  102406. }
  102407. this._ground.receiveShadows = this._options.enableGroundShadow;
  102408. };
  102409. /**
  102410. * Setup the ground material according to the specified options.
  102411. */
  102412. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  102413. if (!this._groundMaterial) {
  102414. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  102415. }
  102416. this._groundMaterial.alpha = this._options.groundOpacity;
  102417. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  102418. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  102419. this._groundMaterial.primaryColor = this._options.groundColor;
  102420. this._groundMaterial.useRGBColor = false;
  102421. this._groundMaterial.enableNoise = true;
  102422. if (this._ground) {
  102423. this._ground.material = this._groundMaterial;
  102424. }
  102425. };
  102426. /**
  102427. * Setup the ground diffuse texture according to the specified options.
  102428. */
  102429. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  102430. if (!this._groundMaterial) {
  102431. return;
  102432. }
  102433. if (this._groundTexture) {
  102434. return;
  102435. }
  102436. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  102437. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  102438. return;
  102439. }
  102440. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102441. diffuseTexture.gammaSpace = false;
  102442. diffuseTexture.hasAlpha = true;
  102443. this._groundMaterial.diffuseTexture = diffuseTexture;
  102444. };
  102445. /**
  102446. * Setup the ground mirror texture according to the specified options.
  102447. */
  102448. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  102449. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102450. if (!this._groundMirror) {
  102451. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  102452. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  102453. this._groundMirror.anisotropicFilteringLevel = 1;
  102454. this._groundMirror.wrapU = wrapping;
  102455. this._groundMirror.wrapV = wrapping;
  102456. this._groundMirror.gammaSpace = false;
  102457. if (this._groundMirror.renderList) {
  102458. for (var i = 0; i < this._scene.meshes.length; i++) {
  102459. var mesh = this._scene.meshes[i];
  102460. if (mesh !== this._ground &&
  102461. mesh !== this._skybox &&
  102462. mesh !== this._rootMesh) {
  102463. this._groundMirror.renderList.push(mesh);
  102464. }
  102465. }
  102466. }
  102467. }
  102468. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  102469. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  102470. };
  102471. /**
  102472. * Setup the ground to receive the mirror texture.
  102473. */
  102474. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  102475. if (this._groundMaterial) {
  102476. this._groundMaterial.reflectionTexture = this._groundMirror;
  102477. this._groundMaterial.reflectionFresnel = true;
  102478. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  102479. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  102480. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  102481. }
  102482. };
  102483. /**
  102484. * Setup the skybox according to the specified options.
  102485. */
  102486. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  102487. var _this = this;
  102488. if (!this._skybox || this._skybox.isDisposed()) {
  102489. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  102490. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  102491. }
  102492. this._skybox.parent = this._rootMesh;
  102493. };
  102494. /**
  102495. * Setup the skybox material according to the specified options.
  102496. */
  102497. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  102498. if (!this._skybox) {
  102499. return;
  102500. }
  102501. if (!this._skyboxMaterial) {
  102502. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  102503. }
  102504. this._skyboxMaterial.useRGBColor = false;
  102505. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  102506. this._skyboxMaterial.enableNoise = true;
  102507. this._skybox.material = this._skyboxMaterial;
  102508. };
  102509. /**
  102510. * Setup the skybox reflection texture according to the specified options.
  102511. */
  102512. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  102513. if (!this._skyboxMaterial) {
  102514. return;
  102515. }
  102516. if (this._skyboxTexture) {
  102517. return;
  102518. }
  102519. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  102520. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  102521. return;
  102522. }
  102523. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102524. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  102525. this._skyboxTexture.gammaSpace = false;
  102526. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  102527. };
  102528. /**
  102529. * Dispose all the elements created by the Helper.
  102530. */
  102531. EnvironmentHelper.prototype.dispose = function () {
  102532. if (this._groundMaterial) {
  102533. this._groundMaterial.dispose(true, true);
  102534. }
  102535. if (this._skyboxMaterial) {
  102536. this._skyboxMaterial.dispose(true, true);
  102537. }
  102538. this._rootMesh.dispose(false);
  102539. };
  102540. /**
  102541. * Default ground texture URL.
  102542. */
  102543. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  102544. /**
  102545. * Default skybox texture URL.
  102546. */
  102547. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  102548. /**
  102549. * Default environment texture URL.
  102550. */
  102551. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  102552. return EnvironmentHelper;
  102553. }());
  102554. BABYLON.EnvironmentHelper = EnvironmentHelper;
  102555. })(BABYLON || (BABYLON = {}));
  102556. //# sourceMappingURL=babylon.environmentHelper.js.map
  102557. var BABYLON;
  102558. (function (BABYLON) {
  102559. /** Internal class used to store shapes for emitters */
  102560. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  102561. function ParticleSystemSetEmitterCreationOptions() {
  102562. }
  102563. return ParticleSystemSetEmitterCreationOptions;
  102564. }());
  102565. /**
  102566. * Represents a set of particle systems working together to create a specific effect
  102567. */
  102568. var ParticleSystemSet = /** @class */ (function () {
  102569. function ParticleSystemSet() {
  102570. /**
  102571. * Gets the particle system list
  102572. */
  102573. this.systems = new Array();
  102574. }
  102575. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  102576. /**
  102577. * Gets the emitter node used with this set
  102578. */
  102579. get: function () {
  102580. return this._emitterNode;
  102581. },
  102582. enumerable: true,
  102583. configurable: true
  102584. });
  102585. /**
  102586. * Creates a new emitter mesh as a sphere
  102587. * @param options defines the options used to create the sphere
  102588. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  102589. * @param scene defines the hosting scene
  102590. */
  102591. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  102592. if (this._emitterNode) {
  102593. this._emitterNode.dispose();
  102594. }
  102595. this._emitterCreationOptions = {
  102596. kind: "Sphere",
  102597. options: options,
  102598. renderingGroupId: renderingGroupId
  102599. };
  102600. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  102601. emitterMesh.renderingGroupId = renderingGroupId;
  102602. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  102603. material.emissiveColor = options.color;
  102604. emitterMesh.material = material;
  102605. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102606. var system = _a[_i];
  102607. system.emitter = emitterMesh;
  102608. }
  102609. this._emitterNode = emitterMesh;
  102610. };
  102611. /**
  102612. * Starts all particle systems of the set
  102613. * @param emitter defines an optional mesh to use as emitter for the particle systems
  102614. */
  102615. ParticleSystemSet.prototype.start = function (emitter) {
  102616. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102617. var system = _a[_i];
  102618. if (emitter) {
  102619. system.emitter = emitter;
  102620. }
  102621. system.start();
  102622. }
  102623. };
  102624. /**
  102625. * Release all associated resources
  102626. */
  102627. ParticleSystemSet.prototype.dispose = function () {
  102628. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102629. var system = _a[_i];
  102630. system.dispose();
  102631. }
  102632. this.systems = [];
  102633. if (this._emitterNode) {
  102634. this._emitterNode.dispose();
  102635. this._emitterNode = null;
  102636. }
  102637. };
  102638. /**
  102639. * Serialize the set into a JSON compatible object
  102640. * @returns a JSON compatible representation of the set
  102641. */
  102642. ParticleSystemSet.prototype.serialize = function () {
  102643. var result = {};
  102644. result.systems = [];
  102645. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102646. var system = _a[_i];
  102647. result.systems.push(system.serialize());
  102648. }
  102649. if (this._emitterNode) {
  102650. result.emitter = this._emitterCreationOptions;
  102651. }
  102652. return result;
  102653. };
  102654. /**
  102655. * Parse a new ParticleSystemSet from a serialized source
  102656. * @param data defines a JSON compatible representation of the set
  102657. * @param scene defines the hosting scene
  102658. * @param gpu defines if we want GPU particles or CPU particles
  102659. * @returns a new ParticleSystemSet
  102660. */
  102661. ParticleSystemSet.Parse = function (data, scene, gpu) {
  102662. if (gpu === void 0) { gpu = false; }
  102663. var result = new ParticleSystemSet();
  102664. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  102665. scene = scene || BABYLON.Engine.LastCreatedScene;
  102666. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  102667. var system = _a[_i];
  102668. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  102669. }
  102670. if (data.emitter) {
  102671. var options = data.emitter.options;
  102672. switch (data.emitter.kind) {
  102673. case "Sphere":
  102674. result.setEmitterAsSphere({
  102675. diameter: options.diameter,
  102676. segments: options.segments,
  102677. color: BABYLON.Color3.FromArray(options.color)
  102678. }, data.emitter.renderingGroupId, scene);
  102679. break;
  102680. }
  102681. }
  102682. return result;
  102683. };
  102684. return ParticleSystemSet;
  102685. }());
  102686. BABYLON.ParticleSystemSet = ParticleSystemSet;
  102687. })(BABYLON || (BABYLON = {}));
  102688. //# sourceMappingURL=babylon.particleSystemSet.js.map
  102689. var BABYLON;
  102690. (function (BABYLON) {
  102691. /**
  102692. * This class is made for on one-liner static method to help creating particle system set.
  102693. */
  102694. var ParticleHelper = /** @class */ (function () {
  102695. function ParticleHelper() {
  102696. }
  102697. /**
  102698. * This is the main static method (one-liner) of this helper to create different particle systems
  102699. * @param type This string represents the type to the particle system to create
  102700. * @param scene The scene where the particle system should live
  102701. * @param gpu If the system will use gpu
  102702. * @returns the ParticleSystemSet created
  102703. */
  102704. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  102705. if (gpu === void 0) { gpu = false; }
  102706. if (!scene) {
  102707. scene = BABYLON.Engine.LastCreatedScene;
  102708. ;
  102709. }
  102710. var token = {};
  102711. scene._addPendingData(token);
  102712. return new Promise(function (resolve, reject) {
  102713. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  102714. scene._removePendingData(token);
  102715. return reject("Particle system with GPU is not supported.");
  102716. }
  102717. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  102718. scene._removePendingData(token);
  102719. var newData = JSON.parse(data.toString());
  102720. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  102721. }, undefined, undefined, undefined, function (req, exception) {
  102722. scene._removePendingData(token);
  102723. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  102724. });
  102725. });
  102726. };
  102727. /**
  102728. * Static function used to export a particle system to a ParticleSystemSet variable.
  102729. * Please note that the emitter shape is not exported
  102730. * @param system defines the particle systems to export
  102731. */
  102732. ParticleHelper.ExportSet = function (systems) {
  102733. var set = new BABYLON.ParticleSystemSet();
  102734. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  102735. var system = systems_1[_i];
  102736. set.systems.push(system);
  102737. }
  102738. return set;
  102739. };
  102740. /**
  102741. * Gets or sets base Assets URL
  102742. */
  102743. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  102744. return ParticleHelper;
  102745. }());
  102746. BABYLON.ParticleHelper = ParticleHelper;
  102747. })(BABYLON || (BABYLON = {}));
  102748. //# sourceMappingURL=babylon.particleHelper.js.map
  102749. var BABYLON;
  102750. (function (BABYLON) {
  102751. /**
  102752. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  102753. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  102754. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  102755. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102756. */
  102757. var VideoDome = /** @class */ (function (_super) {
  102758. __extends(VideoDome, _super);
  102759. /**
  102760. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  102761. * @param name Element's name, child elements will append suffixes for their own names.
  102762. * @param urlsOrVideo defines the url(s) or the video element to use
  102763. * @param options An object containing optional or exposed sub element properties
  102764. */
  102765. function VideoDome(name, urlsOrVideo, options, scene) {
  102766. var _this = _super.call(this, name, scene) || this;
  102767. _this._useDirectMapping = false;
  102768. // set defaults and manage values
  102769. name = name || "videoDome";
  102770. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102771. options.clickToPlay = Boolean(options.clickToPlay);
  102772. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  102773. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  102774. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102775. if (options.useDirectMapping === undefined) {
  102776. _this._useDirectMapping = true;
  102777. }
  102778. else {
  102779. _this._useDirectMapping = options.useDirectMapping;
  102780. }
  102781. // create
  102782. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  102783. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102784. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  102785. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102786. // configure material
  102787. material.useEquirectangularFOV = true;
  102788. material.fovMultiplier = 1.0;
  102789. material.opacityFresnel = false;
  102790. if (_this._useDirectMapping) {
  102791. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102792. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102793. material.diffuseTexture = texture;
  102794. }
  102795. else {
  102796. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  102797. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102798. material.reflectionTexture = texture;
  102799. }
  102800. // configure mesh
  102801. _this._mesh.material = material;
  102802. _this._mesh.parent = _this;
  102803. // optional configuration
  102804. if (options.clickToPlay) {
  102805. scene.onPointerUp = function () {
  102806. _this._videoTexture.video.play();
  102807. };
  102808. }
  102809. return _this;
  102810. }
  102811. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  102812. /**
  102813. * Gets the video texture being displayed on the sphere
  102814. */
  102815. get: function () {
  102816. return this._videoTexture;
  102817. },
  102818. enumerable: true,
  102819. configurable: true
  102820. });
  102821. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  102822. /**
  102823. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102824. * Also see the options.resolution property.
  102825. */
  102826. get: function () {
  102827. return this._material.fovMultiplier;
  102828. },
  102829. set: function (value) {
  102830. this._material.fovMultiplier = value;
  102831. },
  102832. enumerable: true,
  102833. configurable: true
  102834. });
  102835. /**
  102836. * Releases resources associated with this node.
  102837. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  102838. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  102839. */
  102840. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  102841. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  102842. this._videoTexture.dispose();
  102843. this._mesh.dispose();
  102844. this._material.dispose();
  102845. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  102846. };
  102847. return VideoDome;
  102848. }(BABYLON.Node));
  102849. BABYLON.VideoDome = VideoDome;
  102850. })(BABYLON || (BABYLON = {}));
  102851. //# sourceMappingURL=babylon.videoDome.js.map
  102852. var BABYLON;
  102853. (function (BABYLON) {
  102854. /**
  102855. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  102856. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  102857. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  102858. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102859. */
  102860. var PhotoDome = /** @class */ (function (_super) {
  102861. __extends(PhotoDome, _super);
  102862. /**
  102863. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  102864. * @param name Element's name, child elements will append suffixes for their own names.
  102865. * @param urlsOfPhoto define the url of the photo to display
  102866. * @param options An object containing optional or exposed sub element properties
  102867. */
  102868. function PhotoDome(name, urlOfPhoto, options, scene) {
  102869. var _this = _super.call(this, name, scene) || this;
  102870. _this._useDirectMapping = false;
  102871. // set defaults and manage values
  102872. name = name || "photoDome";
  102873. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102874. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102875. if (options.useDirectMapping === undefined) {
  102876. _this._useDirectMapping = true;
  102877. }
  102878. else {
  102879. _this._useDirectMapping = options.useDirectMapping;
  102880. }
  102881. // create
  102882. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102883. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102884. // configure material
  102885. material.opacityFresnel = false;
  102886. material.useEquirectangularFOV = true;
  102887. material.fovMultiplier = 1.0;
  102888. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  102889. // configure mesh
  102890. _this._mesh.material = material;
  102891. _this._mesh.parent = _this;
  102892. return _this;
  102893. }
  102894. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  102895. /**
  102896. * Gets or sets the texture being displayed on the sphere
  102897. */
  102898. get: function () {
  102899. return this._photoTexture;
  102900. },
  102901. set: function (value) {
  102902. if (this._photoTexture === value) {
  102903. return;
  102904. }
  102905. this._photoTexture = value;
  102906. if (this._useDirectMapping) {
  102907. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102908. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102909. this._material.diffuseTexture = this._photoTexture;
  102910. }
  102911. else {
  102912. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  102913. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102914. this._material.reflectionTexture = this._photoTexture;
  102915. }
  102916. },
  102917. enumerable: true,
  102918. configurable: true
  102919. });
  102920. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  102921. /**
  102922. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102923. * Also see the options.resolution property.
  102924. */
  102925. get: function () {
  102926. return this._material.fovMultiplier;
  102927. },
  102928. set: function (value) {
  102929. this._material.fovMultiplier = value;
  102930. },
  102931. enumerable: true,
  102932. configurable: true
  102933. });
  102934. /**
  102935. * Releases resources associated with this node.
  102936. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  102937. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  102938. */
  102939. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  102940. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  102941. this._photoTexture.dispose();
  102942. this._mesh.dispose();
  102943. this._material.dispose();
  102944. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  102945. };
  102946. return PhotoDome;
  102947. }(BABYLON.Node));
  102948. BABYLON.PhotoDome = PhotoDome;
  102949. })(BABYLON || (BABYLON = {}));
  102950. //# sourceMappingURL=babylon.photoDome.js.map
  102951. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\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}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#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 mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin float angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\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\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\n\n#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 mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nin float angle;\n#else\nin vec2 angle;\n#endif\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\n#ifdef ANGULARSPEEDGRADIENTS\nout float outAngle;\n#else\nout vec2 outAngle;\n#endif\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANGULARSPEEDGRADIENTS\nuniform sampler2D angularSpeedGradientSampler;\n#endif \n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\n#ifndef ANGULARSPEEDGRADIENTS \noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#else\noutAngle=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n#endif \n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*randoms2.z))*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(age/life,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\n#ifdef ANGULARSPEEDGRADIENTS\nfloat angularSpeed=texture(angularSpeedGradientSampler,vec2(age/life,0)).r;\noutAngle=angle+angularSpeed*timeDelta;\n#else\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#endif\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","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;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","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\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  102952. 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}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};